Screen is one of these programs that can save your life if you know how to use it.
Every single user of Terminal knows ssh, because one often needs to connect on remote machines. Also, most clusters, servers and complex computing architectures don’t have a nice visual interface and are only accessible via ssh.
However, you might have noticed that when losing ssh connection, the console you were working in is closed, and information lost. Even worse, if a program was running, its execution is interrupted.
The problem is very common, and was solved many years ago by the introduction of multi-terminal utilities.
Screen is a very powerful programs; it multiplexes the terminal into multiple shell windows. The most interesting part is that you can close the window without interrupting screen, nor the programs running within it.
Screen is a rather complex program, with unlimited possibilities in terms of usability and complex use, as the man page can attest. But the few basic commands detailed below are very sufficient in many situations. For special use, one can read the manual and various other blogs to delve into the counless features of screen.
In a terminal, you may start a screen session by typing the screen command.
A secondary session is opened in the main one. The big difference between the two is that the screen session might be resumed from any other sh session within your user session, as screen is always running as background task.
Consequently, if you close the terminal window and you want to go back to you screen session, you just need to type
This simple concept enables various powerful manipulations. You can name and launch multiple sessions; each of them may be “detached” and “attached” when needed.
For example, I can run the top command (to monitor cpu and memory use) in a screen named “toptask” as a background task using
$ screen -mdS toptask top
With the “-mdS” tag, the session is named and automatically detached. You can see the ongoing screen sessions with
And get back to any of them, for example “toptask” (i.e. “attach” it) with
Now with ssh: if you want to launch a command on a remote machine in a screen session, just use
$ ssh user@machine -C screen -mdS screensession mycommand
which creates a secured ssh link, opens a screen session on the machine, runs the command and detaches the window. In other words, your command is executed on the remote machine, but you won’t see anything on your own. To see what is happening, connect to the machine and search for your screen session:
$ ssh user@machine
$ screen -list
$ screen -r screensession
In conclusion, with screen you can run complex programs and commands (especially those that last long) on remote machines without fearing to lose ssh connection and interrupting execution.