The screen Command — Persistent Terminal Sessions
Overview
screen is a terminal multiplexer that lets you create persistent shell sessions. If your SSH connection drops — due to a timeout, network issue, or closing your laptop — any process running inside a screen session keeps running. You can reconnect later and pick up right where you left off.
This is essential for long-running tasks like database imports, large file transfers, software compilations, or any operation that shouldn’t be interrupted.
Starting a Session
Create a new session
screen
Create a named session (recommended)
screen -S backup
Naming sessions makes it easy to identify and reattach to the right one.
Detaching from a Session
While inside a screen session, press:
Ctrl + A, then D
This detaches you from the session — it continues running in the background. You’ll see a message like:
[detached from 12345.backup]
Your SSH session is now free, and the screen session is still active.
Reattaching to a Session
Reattach to the most recent session
screen -r
Reattach to a named session
screen -r backup
Reattach to a specific session by ID
screen -r 12345
Force reattach (if the session is still marked as attached)
screen -d -r backup
This detaches any other connection to the session first, then reattaches you.
Listing All Sessions
screen -ls
Sample output:
There are screens on:
12345.backup (Detached)
12346.migration (Attached)
2 Sockets in /var/run/screen/S-username.
Ending a Session
From inside the screen session, simply type:
exit
Or press Ctrl + D. The session is terminated when the last shell inside it exits.
Essential Keyboard Shortcuts
All screen shortcuts start with Ctrl + A (the command prefix), followed by a key:
| Shortcut | Action |
|---|---|
Ctrl+A, D | Detach from current session |
Ctrl+A, C | Create a new window within the session |
Ctrl+A, N | Switch to the next window |
Ctrl+A, P | Switch to the previous window |
Ctrl+A, " | List all windows in the session |
Ctrl+A, K | Kill the current window |
Ctrl+A, [ | Enter scroll/copy mode (use arrow keys, press q to exit) |
Practical Hosting Examples
Run a database import that takes hours
screen -S db-import
mysql -u username -p database_name < large-database.sql
# Detach with Ctrl+A, D — the import continues in the background
Run a long file transfer
screen -S transfer
rsync -avzP /source/ user@remote:/destination/
# Detach safely
Run a script that processes data overnight
screen -S processing
python3 process_data.py
# Detach and come back in the morning
Tips
- Always use
screen(ortmux) for any task that takes more than a few minutes. SSH disconnections are common and can interrupt critical operations. - Give your sessions meaningful names with
-Sso you can easily identify them later. - If
screenis not installed, ask your hosting provider or install it withsudo apt install screen(Debian/Ubuntu) orsudo yum install screen(CentOS/RHEL). tmuxis a modern alternative toscreenwith similar functionality and additional features.