Jonty Behr  •  02 Oct 2017

Keep your long running commands alive with Screen

Sometimes we need to SSH into a remote server and execute a long running process. However, one of the problems with this is that if your SSH connection is lost, then the remote process will be interrupted. Or, perhaps you need to run multiple commands at the same time, which would ordinarily necessitate having multiple SSH sessions open simultaneously.

There is an easy way around this - by using screen or tmux. There are pros and cons to each of these tools, but they perform pretty much the same function - allowing you to keep a remote process running (even if your SSH connection is lost) and having multiple virtual terminals open at the same time. In this quick introduction, I'll go through some steps on how to get started and some basic commands for screen.

Installation

Installation on ubuntu can be done through the repositories: sudo apt-get install screen.

Basic Commands

Getting started with screen is easy. To start up a new screen terminal, just type screen. You'll see some information about screen, after which you can press the spacebar or Return to continue. After that, you'll have a fully functional command prompt.

As we go through the next steps, bear in mind that once you are inside an active screen terminal, most screen commands are prefixed with CTRL + A.

Disconnecting

To disconnect from your screen terminal (but leave it running in the background), you can issue the following command:

CTRL + A
d

Once you have done this, you can safely perform any other actions that you want, and your screen terminal will continue running in the background. You can even completely disconnect from your SSH session and then reconnect, safe in the knowledge that screen is still running. Pretty awesome!

Reconnecting

To reconnect back to an existing screen terminal, you can type screen -r. If there is no existing screen terminal, then you'll get a message that There is no screen to be resumed.

Add a new screen

If you already have a screen terminal open, you can create additional virtual terminals by typing CTRL + A followed by c. You can continue adding as many virtual terminals as you wish (limited by the host machine's specs).

Navigation

From now on, I'm going to leave out the CTRL + A command (although you will need to type this as usual).

Close an active terminal

To close an active terminal, you can type exit (without the CTRL + A prefix). If you do this with only one virtual terminal open, then screen will exit completely.

Help

To get a full list of all screen commands, type CTRL + A followed by ?.

Conclusion

That's it for our basic introduction to screen. Hopefully you're already starting to see how useful this tool can be. In our next tutorial we'll show you some more tips on how to become even more productive in screen.