Recovering Disconnected Sessions Using screen

Problem

You run long processes over SSH, perhaps over the WAN, and when you get disconnected you lose a lot of work. Or perhaps you started a long job from work, but need to go home and be able to check on the job later; you could run your process using nohup, but then you won’t be able to reattach to it when your connection comes back or you get home.

Solution

Install and use GNU screen.

Using screen is very simple. Type screen or screen -a. The -a option includes all of screen’s capabilities even at the expense of some redraw (thus bandwidth) efficiency. Honestly, we use -a but have never noticed a difference.

When you do this, it will look like nothing happened, but you are now running inside a screen. echo $SHLVL should return a number greater than one if this worked (see also :L$SHLVL in Customizing Your Prompt). To test it, do an ls -la, then kill your terminal (do not exit cleanly, as you will exit screen as well). Log back into the machine and type screen -r to reconnect to screen. If that doesn’t put you back where you left off, try screen -d -r. If that doesn’t work, try ps auwx | grep [s]creen to see if screen is still running, and then try man screen for troubleshooting information—but it should just work. If you run into problems with that ps command on a system other than Linux, see Finding Out Whether a Process Is Running.

Starting screen with something like the following will make it easier to figure out what session to reattach ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.