Using a the "screen" command to keep you sessions safe

A typical problem when connecting to a remote machine is that if the connection drops, the remote server will believe we are no longer interested in it and will kill our session. If we were performing some analysis, it will be terminated and we'll have to run it again.

Sometimes the analysis is long, and even if we have a stable connection we would need to keep our computer on just to let the remote server knowing we don't want to close the session. There is a handy tool to make our life easier: screen.

With screen we can create a terminal that will not disappear when we disconnect from a machine, and that will wait for us to come back when reconnecting to the server.

How to use screen

In this section we'll see how to (1) create a new working session, (2) how to connect to an existing session and (3) some tricks to use screen as a pro.

To create a screen session

  1. Log in into the remote machine
  2. First of all, we have to check no other screen session is active:
    screen -list
  3. If the previous command gives no output (or a message like No Sockets found in …), then we can create a new screen
  4. To create a new screen session, type this command:
    screen -S course

    With the -S switch we gave our session a handy nickname (“course”), but it's not mandatory to do so, but can be very helpful.

  5. Now we are inside our “screen” and we'll have to press ENTER to get rid of a welcome text. If we close the terminal window, we don't lose what we were doing.

To reconnect to an existing screen session

  1. To re-attach to our previous screen:
    screen -dr course

Interacting with the screen program

Since the screen program shows us a Linux terminal, when we type we are talking to the terminal itself. So to interact with screen we need a special shortcut: Ctrl + A. This triggers screen to listen to us. Then we can type a second key to specify what we needed:

  • Ctrl + A, C to create a new terminal inside our session
  • Ctrl + A, P to navigate to the P revious terminal
  • Ctrl + A, N to navigate to the Next terminal
  • Ctrl + A, D to Detach from the session: we'll return back to the “parent” terminal where we can reattach to the screen session with screen -r course.

Further reading

For a more information you can read this article about screen.