DEV Community

fceruti
fceruti

Posted on

Juggling server tasks with screen

Let’s say you have a server where you need run a script that will create a backup file which will take 40 minutes, install some software for 15 minutes, and finally while all of this is happening, you need to investigate the log files.

A first approach would be to just open a new terminal windows for each task and create a new ssh connection on each. While this works fine, a big problem is that if your connection breaks, the processes are terminated.
A second approach may be to run the first two in the background and then explore your logs

nohup sh backup_db.sh &>/dev/null &
nohup sh install.sh &>/dev/null &
tail /var/logs/my_logs
Enter fullscreen mode Exit fullscreen mode

This will make sure that even if you connection breaks, the processes will keep running, but you’ll either have no output data, or have to check some logs somewhere to see if how the processes finished.

Screen comes to the rescue. Screen basically creates a terminal within a terminal. When you type on an empty prompt screen, you then see another empty prompt just like the one you had before, but this new prompt is different: it is not tied to your session and connection, but to the screen process in the OS.

What this means is that if you can now type sh backup_db.sh, start seeing messages from your script telling you about the progress of the backup, and then press ctrl + a ctrl + d (detach), and everything will be quiet again. You would have returned to the prompt where you typed screen in the first place.

You shut down your computer, go home, have some dinner, drink a beer, ssh from your laptop, and re attach to screen with screen -r, and you’ll be back to the log messages sent by the backup script who has been working all this time for you.

Back to the original problem. The way I would handle the tasks at hand would be the following:

# Start screen
> screen

# Run backup scrip
> sh backup_db.sh

# Create a new screen
# ctrl + a ctrl + c

# Install software
> sh install.sh

# Detach from screen
# ctrl + a ctrl + d
Enter fullscreen mode Exit fullscreen mode

And finally I'd be free to investigate that weird bug in the logs. After a while, when I want to checkout on the processes, I would just type screen -r to re attach and ctrl + a ctrl + n to cycle through the opened screens.

Top comments (0)