Sometimes we need to execute some time-consuming even everlasting tasks on our server. If we lose connection to the server those tasks will interrupt and stop running. Screen is a perfect command to solve this problem.
Create a new screen
Just type screen
to create a new screen. It will prompt up with some words. Ignore it. Just type space or enter to continue. After that you are in a new screen where you can run time-consuming task.
Once the task is running and you want to leave it running there comes the most magic part of screen. Type ctrl a + d
to detach from current screen. After that you will be in main screen and your task will keep running in the background.
List all screens
screen -list
will list all your screens. The output will be something like this:
There are screens on:
26243.pts-0.ip-172-31-22-134 (04/06/2018 03:39:26 PM) (Detached)
25118.pts-0.ip-172-31-22-134 (03/14/2018 10:34:28 AM) (Detached)
2 Sockets in /var/run/screen/S-ubuntu.
At the beginning of each line there is a series of number like 26243
and 25118
above. These numbers are the process ids of each screen which could be used to reattach the screen.
Reattach a screen
screen -r [session]
will help you reattach a screen from main screen. The parameter session is the process id of the screen you want to reattach. If there is only one screen the parameter could be omitted. After a screen is reattached and the task is finished you can run exit
to exit the current screen.