O'Reilly logo

bash Cookbook by Cameron Newham, JP Vossen, Carl Albing

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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, "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, "Finding Out Whether a Process Is Running."

Starting screen with something like ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required