While working with remote servers, sometimes we need to run long-running scripts. Imagine you are running such a script on your remote server and suddenly the internet connection drops, this will terminate the SSH session, and your work will be lost. For situations like this, we can use the
GNU Screen is a terminal multiplexer program. Simply put, it gives you the ability to launch a number of windows (virtual terminals) from a single screen session. You can connect to a remote machine, start a
screen session, and launch a process, even if the connection is lost, after reconnecting to the remote host, your process will still be running. Let's see how we can use the screen command.
- When we type
screenin the shell, we are presented with license information of the program. Upon pressing
screenprocess will start.
- The shell looks the same as before, If we do a
screen -lscommand, it will show the current screen session.
- Let's mimic a long-running script in this screen session and
ping google.comand detach this screen, please
ctlr+A + dto detach from the screen. Another way to detach an attached screen is to run
screen -d <screen_name>.
ubuntu@ip-172-31-29-101:~$ screen -ls There are screens on: 92359.pts-2.ip-172-31-29-101 (06/30/2021 03:22:38 AM) (Attached) 1 Sockets in /run/screen/S-ubuntu. ubuntu@ip-172-31-29-101:~$ screen -d 92359.pts-2.ip-172-31-29-101 [92359.pts-2.ip-172-31-29-101 detached.] ubuntu@ip-172-31-29-101:~$ screen -ls There are screens on: 91297.logs (06/30/2021 02:10:32 AM) (Detached) 1 Sockets in /run/screen/S-ubuntu.
- After detachment, we are now in the parent shell, if we do
screen -lsnow, we can see the detached screen with its name. Since we have not passed any name, while creating the screen, we get a default name. In order to create a named screen, use
screen -S <screen_name>, note its a capital
$ screen -S logs $ screen -ls There are screens on: 91297.logs (06/30/2021 02:10:32 AM) (Attached) 2 Sockets in /run/screen/S-ubuntu.
- In the parent shell, we can run any program and the ping command will keep on working in the background. We can re-attach to the screen session, we will see
pingcommand still working. In order to re-attach we use
screen -r <screen_name>.
ubuntu@ip-172-31-42-95:~$ screen -r 12108.pts-0.ip-172-31-42-95
- Let's detach this session again using
ctrl+a + dand this time let's disconnect the ssh session as well. Upon reconnection, we will find the same
pingcommand running inside the screen.
reattachingallows devs to run long-running scripts without the fear of losing connection over ssh. To kill a
exitcommand or press
ctrl+a + k.
- In order to kill a screen session.
screen -X -S <screen_name> quit