Running scripts in background with screen command on Ubuntu/Linux
Posted on Jul 04, 2022 ‐ 3 min read
SSHing and executing long-running scripts but only to see it interrupted due to a network reset?
Imagine you have a script that takes several hours to complete. You want to run it in the background.
Well, we all have had that moment where we wanted to execute a long-running script/job but only to find out that it exited due to network disconnection.
I had one similar business requirement where I was running a script that takes more than 24 hours to complete. After multiple tries, I couldn't find a way to complete the job successfully.
Until I found this in-built
screen command which helps run a script in the background. If you don't have the screen installed you can run
sudo apt install screen to install it.
The screen command works by opening a new virtual terminal session. Run the
screen command in the terminal and press
enter and you will see a new terminal session with a new screen session. Whatever you do in this session will not be affected by the main terminal session.
You can use the following screen commands to interact with the screen session:
- Create a new screen session:
screen -S <session-name>. -S is short for session the name.
- To return to the main terminal session press
- To return to the virtual screen session use command
- To list the screen sessions run command
- To choose a different screen session you can use pid or session name. Run
screen -r <pid-or-session-name>.
You can also run the command directly in the background.
screen -d -m <script command>
After running multiple sessions if you want close a few or all of the sessions you can use the following command:
- To delete all the sessions you can use
- To only delete the current session use
screen -X quitor just
- To kill a specific session from the main terminal use
screen -X -S <pid-or-session-name> kill.
That's all about running scripts in the background. You can find more information about this in the following links:
You can also tweet me at @vipiny35 if you have any questions or suggestions.