Skip to main content

How to Keep SSH Sessions Running in the Background Using Screen

Lost your SSH connection during a long task? Learn how to use the screen command to keep terminal processes running safely in the background.

If your network connection drops during a long terminal task (like over SSH), the running process usually stops. This guide shows you how to use the screen command to keep your session and tasks running in the background, even if your connection to the server is interrupted. This guide is aimed at users performing site maintenance via the command line (SSH).

Prerequisites

  • SSH access to your site's server.

  • Basic understanding of the command line (terminal).

Step-by-Step Instructions

  1. Start a new screen session: Once connected to the server via SSH, type the command screen and press Enter. You are now in a new session that looks just like a normal terminal.

  2. Run your commands: Start your long-running script or task as you normally would.

  3. Detach from the session: You can leave the session while keeping the process running in the background. While inside the session, the easiest way to detach is to press Ctrl + A, followed by the D key.

  4. List active sessions: If your connection drops unexpectedly or you want to check on background tasks, reconnect to the server and run the command screen -ls. This lists all your active sessions.

  5. Resume a session: You can return to a background session by typing screen -r. If you have multiple sessions open, add the session's ID number to the command (e.g., screen -r 12345).

Example Terminal Output

Example of listing screen sessions (using the screen -ls command):

$ screen -ls
There is a screen on:
12345.<sitename> (Detached)
1 Socket in /run/screen/S-user.

Troubleshooting

  • I'm trying to resume a session but get the error "There is no screen to be resumed": Run screen -ls to verify that the session still exists and its status is listed as (Detached).

  • The session status is (Attached) and I can't access it: If your connection dropped suddenly, the session might still think it's open in your previous window. You can force it to detach and then immediately resume it with a single command: screen -d -r.

  • How do I completely close a screen session? When you are inside the screen session and your tasks are finished, you can close the session entirely by typing exit or pressing Ctrl + D.

Related Articles

Summary

By using the screen command, you can avoid issues caused by dropped connections and safely keep your processes running, no matter what happens to your network. This makes running long scripts and bulk updates much more reliable.

Did this answer your question?