How To Autostart Screen Session On Linux When Logging In
A few days ago, we have seen how to autostart Tmux session whenever you log in to a Linux system either locally or remotely via SSH. Today, we are going to see how to autostart Screen session on Linux when logging in. Auto-starting Screen sessions will greatly help when running a long running process via SSH. If you lost the network connectivity for any reason, the process will keep running inside the Screen session in the remote system and you can reattach to it when the network comes back online.
Autostart Screen Session On Linux When Logging In
To autostart Screen session on Linux, edit your Linux system’s ~/.bash_profile or ~/.bashrc file:
$ nano ~/.bash_profile
If the above file is not available, just create it.
And add the following lines in it:
if [[ -z "$STY" ]]; then screen -xRR default fi
Here, we used -x flag to attach to a not detached screen session. And the -RR flag attempts to resume the youngest (in terms of creation time) detached screen session it finds.
Note: If you use Zsh shell, add the above lines in ~/.zshrc file.
Save and close the file. Log out and log back into the system. You will be landed into a new Screen session named ‘default’.
Now, start any process inside the Screen session and detach it from by pressing Ctrl+a followed by d. The process will keep running inside the Screen session even if the network connect gets disconnected. Once the network connect is back, you can again SSH into the remote system and you will see that the job is still running!!
Have a look at the following animated demo:
Let me clarify what I just did in the above output.
- I connect to my remote Ubuntu server via SSH from my local system. A new Screen session named “default” is automatically started.
- Inside the Screen session, I run a command (Ex. watch grep \”cpu MHz\” /proc/cpuinfo) to monitor the CPU speed.
- Then, I detached from the session by pressing Ctrl+a and d.
- And then, I list the Screen sessions using “screen -ls” command and exit the SSH session.
- Finally, I reconnect to the remote system via SSH and verify if the process is keep running inside Screen session without any interruption.
Hope you understand.
To stop auto-starting Screen session, simply delete the lines that added earlier from the your remote system’s ~/.bashrc or ~/.bash_profile file.