When administering a remote Ubuntu server via SSH, network instability can cause your connection to drop unexpectedly. If you are in the middle of a lengthy compilation, database migration, or system update, a dropped SSH connection will instantly kill the running processes. By configuring your server to automatically launch GNU Screen upon login, you ensure that every session is persistent and safe from network disruptions.
How the GNU Screen Utility Works
GNU Screen is a terminal multiplexer that runs on the server. When you start a process inside a Screen session, it detaches from your physical SSH connection. If your Wi-Fi drops or you close your laptop, the process continues running safely on the server. When you reconnect, you simply reattach to the existing Screen session and resume exactly where you left off.
How to Install GNU Screen
First, ensure the utility is installed on your Ubuntu server.
- Log into your Ubuntu server via SSH.
- Update your package lists:
sudo apt update - Install the package:
sudo apt install screen -y
How to Configure Automatic Screen Attachment on Login
To automate the process, we will append a small bash script to your user profile. This script will check if you are connecting via SSH. If you are, it will look for an existing detached Screen session to resume. If no session exists, it will create a brand new one automatically.
- While logged into the server, open your bash profile using the nano text editor:
nano ~/.bash_profile(If the file does not exist, nano will create it). - Scroll to the very bottom of the file.
- Copy and paste the following bash script:
if [ -z "$STY" ] && [ -n "$SSH_CONNECTION" ]; then screen -xRR fi - Press Ctrl + O followed by Enter to save the file.
- Press Ctrl + X to exit the nano editor.
The -xRR flag is critical: it tells the system to force an attachment to the most recent detached session, or create a new session if none exist. The $STY check ensures that the script does not try to launch a Screen session inside another Screen session, which creates an infinite loop.
How to Test the Automation
To verify the setup, type exit to close your current SSH connection. Log back into your server normally. You should notice a brief flash as the terminal clears itself, indicating that you have been dropped directly into a new Screen environment. If your connection ever drops, simply SSH back in, and you will be instantly reunited with your running processes.