Software and Programming

GNU screen – persistent terminal sessions

So, you open a terminal, ssh to some server, start a long-running command and suddenly –
there’s a power cut / Moba or whatever program you are using dies / windows restarts

Is it all lost?
Well, yes. But there’s a way to avoid it:

use screen.

screen (aka GNU screen, for easier googling) is basically a session manager for the terminal.
To start it, ssh to your server and type “screen”.

You will notice that the screen clears and you’ve got another shell prompt. This shell is running under the screen session.

You can work in the shell as normal (i.e, starting an interactive command, ssh to another server, etc), or you can send commands to the screen session using the Ctrl-A key combination (^a).

To get a list of screen commands, type Ctrl-A ?
(or better yet, look up a cheatsheet)

To detach from the screen session, type Ctrl-A d
– this will get you out of the session, but leave screen running.

You can re-attach to the running screen from any other terminal session by typing screen -r

If you’ve left the screen session running in another terminal, you can take it over in your current terminal by typing the command screen -rd.

So, to put together what we’ve learned:

Start a screen session:

Start a slow-running command in the shell:

$OUR_ROOT/tools/Foo/ -in ……

Leave it running, or detach with Ctrl-A d

Go home, reconnect to work (or go for lunch, come back after your machine rebooted by accident or whatever), ssh to the server where you ran screen, and type

screen -rd

to see if your script finished and carry on from where you left.

You leave screen by exiting all the shells you have open under the screen session, or with a keyboard shortcut I can’t be bothered to look up.

Bonus tips (i.e, all the screen commands my fingers know):

Ctrl-A c = open another shell session inside screen

Ctrl-A Ctrl-A = toggle between the two most recent open shell sessions

Ctrl-A ” = see a list of open shell sessions

Ctrl-A A = give a name to the current shell session

Ctrl-A ‘ = switch to a named shell session by typing (the start of ) its name.
Hope you find this useful,