Intro to Linux Screen
October 22, 2020
Background
The linux screen
utility allows you to run commands or programs in the background easily. This is great for when you need to multi-task or simply run programs without being attached to them. screen
is pre-installed on most linux systems but can be easily installed if not. For Debian based systems, run the below.
sudo apt install screen
For others, use their respective package manager (ex: yum
for centOS)
Using screen
To start a session, run screen with the name of the session
screen -S web_server
Now you are in the new session and can run any command or program. We will run a simple sleep and echo to emulate some long running task.
sleep 30 && echo "Hi"
Detaching from the screen
Now that the 30 second “program” is running, you can detach from it so that it can run in the background while you work on something else.
To detach from the session, hit CTRL a d
. That is hold the CTRL
key, then a
and d
Listing your screens
To list all the current sessions, run
screen -ls
Reattaching to the screen
After 30 seconds has passed, re-attach to the screen to see the program output. To re-attach run
screen -r web_server
You should see it echo-ed "Hi"
Starting screens detached from the start (programmatically)
Creating a screen and then running a command works fine as a user but does not work well in scripts (programmatically). For this, you can run a screen in detached mode from the start. To executed screen in detached mode run
screen -d -m [command] -S [session_name]
-d
means to run in daemon mode (detached from start).-m
is the command to run.-S
is the name of the session as we have learned before.
Sending commands to the program running in screen
To send a command to the program running inside screen, as opposed to a program for screen to run, use the -X stuff
.
Assuming you had a screen running a backup job that asks for a remote location when run, you could “stuff” the url in.
screen -S backup_job -X stuff s3://my_bucket/backup^M
This would pass s3://my_bucket/backup
to your backup job and the escape sequence for the enter
key.
Ending screens
screen -S [session_name] -X quit #Kill a specific screenkillall screen #Kill all screens
Configuring your screen
Screen windows can be configured per user using a ~/.screenrc
file or system wide using a /etc/screenrc
file.
Custom screen configuration can also be passed per screen invocation using the -c
flag.
A sample screenrc
is linked here.