Have you ever encountered the dreaded “Connection closed by foreign host” message when you were logged into a remote server via SSH and you were in the middle of some important task? You have most probably just lost your session and you will have to start your task all over again. Well, you can prevent this from happening by using the screen command available in most UNIX and Linux distributions.
The screen tool can save you from disconnection disasters and can increase your productivity by using multiple terminal sessions within one SSH session.
Starting a screen session
Screen can be started from the command line as:
ibrahim@anfield:~$ screen -S mysession
‘mysession’ is the name given to identify the session. You can change it as necessary. All the screen commands start with Ctrl-a. To get a list of the available screen commands and their bindings type Ctrl-a ? (‘Control-a’ followed by ‘?’ character) within a screen session.
Leaving a screen session
To permanently close the screen session, you can use the ‘exit’ command as would normally do to logout from a terminal session. You can also use the Ctrl-a k key combination to kill the screen session.
To have the screen session running in the background, you will need to detach from the screen terminal by using Ctrl-a d. This will allow all the processes started within the screen terminal to continue running without any interruption.
Resuming a screen session
Most often, you will need to resume a screen session after a dropped connection. Before resuming a screen session, you will need to determine the session name from the screen session list.
ibrahim@anfield:~$ screen -ls There are screens on: 6575.weekend-ftpjob (Saturday 23,May,2009 11:24:32 SGT) (Detached) 6556.kernel-compile (Saturday 23,May,2009 11:23:50 SGT) (Detached) 2 Sockets in /var/run/screen/S-ibrahim.
Here you see two different screen sessions. To resume the ‘weekend-ftpjob’ session, run screen as follows:
ibrahim@anfield:~$ screen -r weekend-ftpjob
You should now be re-attached to the screen.
There are a dozen more things you can do with screen, for example, logging of the screen window, suspend a screen session, monitor for inactivity, etc. To find out more, refer to the screen man page.