Why Use screen?
When you connect to a remote Linux server via SSH, everything running in your terminal is tied to that SSH connection. If your Wi-Fi drops or you close your laptop while running a long task—like downloading a multi-gigabyte file with wget, running a database migration, or compiling code—the process is abruptly terminated.
GNU screen is a terminal multiplexer that solves this problem. It lets you:
- Keep programs running in the background even after you disconnect from SSH.
- Run multiple interactive shells inside a single terminal connection.
- Split your terminal view into upper/lower or left/right regions to monitor multiple tasks at once.
1. Installation
Many Linux distributions pre-install screen. You can check if it is already available by running:
|
|
If it is not installed, install it with your distribution’s package manager:
Debian / Ubuntu:
|
|
RHEL / CentOS / AlmaLinux / Rocky Linux / Fedora:
|
|
2. General Usage Structure: How screen Works
Before memorizing commands, it helps to understand the three-layer mental model of screen:
|
|
- Session: A persistent workspace managed by
screenin the background. You can detach from a session (leave it running) and re-attach to it later. - Window: Inside a single session, you can create multiple independent shell instances (like browser tabs), numbered
0,1,2, etc. - Region (Split Screen): You can divide your physical terminal view into upper/lower (or left/right) panes, and display a different Window in each pane.
The Prefix Key: Ctrl + a
Inside a screen session, normal typing goes directly to the shell. To tell screen that you are issuing a control command, you press Ctrl + a first, release both keys, and then press the command key.
- Example:
Ctrl + athen?opens the built-in help screen (pressSpaceorEnterto exit help). - Need to send a literal
Ctrl + ato the shell? (e.g., to jump to the beginning of a line in bash): pressCtrl + athena. - Note: Case matters!
Ctrl + athensis different fromCtrl + athenS(Shift + s).
3. Session Control
Session control handles creating workspaces, leaving them running in the background, switching back into them, recovering from dropped connections, and terminating sessions when finished.
Create a Session
You can start an unnamed session simply by typing screen, but naming your session with -S is much easier to manage later:
|
|
Detach from a Session (Leave It Running)
Suppose you started a long command (for example, ping 8.8.8.8 or a large system upgrade) and want to leave it running in the background:
- Inside the session, press
Ctrl + athend.
You will return to your original shell and see a message like:
|
|
Your processes inside that session are still running safely in the background. You can now safely log out of SSH.
List and Switch (Re-attach) to a Session
To see all running sessions on the server:
|
|
Example output:
|
|
To re-attach (switch into) a session:
- If you only have one session running:
1screen -r - If you have multiple sessions, specify the session name, PID, or a unique prefix:
1 2 3screen -r download-job # or by PID prefix: screen -r 20451 - To switch between two different sessions: Detach from your current session first (
Ctrl + athend), and then attach to the other session from your main shell (screen -r db-backup).
Recovering from Dropped SSH Connections & Dead Sessions
If your SSH connection drops unexpectedly (for example, due to network loss) while you had a session open, screen -ls may still show the session as (Attached). If you run screen -r, it will refuse to connect because screen thinks you are still connected elsewhere.
- Force detach and re-attach (
-d -r): Detaches the stuck session from the old ghost connection and immediately attaches it to your current terminal:1screen -d -r download-job - Re-attach to the most recent session or create one (
-R):1screen -R - Clean up dead sessions (
-wipe): If a session crashed or was killed uncleanly and shows up as(Dead ???)inscreen -ls, remove the leftover socket files with:1screen -wipe
Kill / Terminate a Session
Once your work is done, you can close the session in several ways:
- Graceful exit (Recommended): Type
exit(or pressCtrl + d) in every shell window inside the session. When the last window closes, you will see[screen is terminating]. - Force kill current window/session from inside: Press
Ctrl + athenk, and pressyto confirm. - Terminate an entire session and all its windows from inside: Press
Ctrl + athen\, and pressyto confirm. - Kill a session from outside (normal shell):
1screen -XS download-job quit
4. Screen Management: Windows, Splitting, Scrolling & Logging
Instead of opening multiple SSH connections, you can create multiple shell windows, name them, split your terminal screen into panes, scroll through command history, and log terminal output inside a single screen session.
Managing & Naming Windows (Virtual Tabs)
Inside a session, you can create and switch between multiple independent shell windows:
| Shortcut | Action |
|---|---|
Ctrl + a then c |
Create a new window with a fresh shell |
Ctrl + a then A |
Rename the current window (e.g., nginx-logs, db-shell) |
Ctrl + a then w |
Show the list of open windows in the status bar |
Ctrl + a then " |
Open an interactive menu of windows (use Up/Down arrows to pick) |
Ctrl + a then n |
Switch to the next window |
Ctrl + a then p |
Switch to the previous window |
Ctrl + a then 0–9 |
Jump directly to window number 0–9 |
Ctrl + a then Ctrl + a |
Toggle back to the previously viewed window |
Ctrl + a then C |
Clear the contents of the current window |
Tip — Name Your Windows (
Ctrl + athenA): Once you have 3 or 4 windows open, seeing0 bash,1 bash,2 bashin the window picker (Ctrl + athen") gets confusing. PressCtrl + athenA(uppercaseA), backspace outbash, and type a descriptive title likeapi-serverortail-log.
Splitting the Screen (Upper / Lower & Left / Right)
Why is My New Split Pane Blank? (Session vs. Window vs. Region)
A very common beginner pitfall: when you split the screen in screen, the new pane (Region) is completely empty at first—it does not automatically launch a shell! If you start typing right after splitting, your keystrokes still go to the original pane, or do nothing if you switched to the empty pane.
To use a newly split region, you must move your focus into it (Ctrl + a then Tab) and then assign a Window to it—either by creating a new window (Ctrl + a then c) or picking an existing one (Ctrl + a then ").
Step-by-Step: Split into Upper and Lower Sections
- Press
Ctrl + athenS(uppercaseS) to split the screen horizontally into an upper and lower region. - Press
Ctrl + athenTabto move your cursor focus into the empty lower region. - Press
Ctrl + athencto start a new shell in that lower region (or pressCtrl + athen"to pick an already-running window).
Split Commands Cheat Sheet
| Shortcut | Action |
|---|---|
Ctrl + a then S |
Split the current region horizontally (upper and lower panes) |
Ctrl + a then | |
Split the current region vertically (left and right panes, in modern screen) |
Ctrl + a then Tab |
Switch focus to the next split region |
Ctrl + a then X |
Close only the current split region (the shell window keeps running in the background) |
Ctrl + a then Q |
Unsplit: close all other regions and keep only the current region full-screen |
Scrolling Up & Copy Mode (Ctrl + a then [)
When beginners use screen for the first time and try to scroll up using the mouse wheel or Shift + PageUp, it often scrolls the local terminal window outside of screen or cycles through bash command history instead of scrolling screen’s output buffer.
To scroll back through output or copy text inside screen, use Copy / Scrollback Mode:
- Press
Ctrl + athen[(orCtrl + athenEsc). You are now in Copy Mode. - Navigate / Scroll: Use the
Up/Downarrow keys,PageUp/PageDown, orCtrl + u/Ctrl + dto scroll up and down through terminal output. - Search text: Press
/(search forward) or?(search backward), type your search term, and pressEnter. - Copy text (Optional): Move the cursor to where you want to start copying and press
Space. Move the cursor to the end of the selection and pressSpaceagain to copy it toscreen’s internal clipboard. - Paste text: Inside any window in the same
screensession, pressCtrl + athen]to paste the copied text. - Exit Scroll Mode: Press
Esc(orq) at any time to return to normal shell typing.
Session & Window Output Logging (Ctrl + a then H)
screen can record everything that happens inside a window—both the commands you type and all terminal output—directly to a file. This is especially useful for auditing production maintenance, saving long build outputs, or debugging errors later.
How to Enable and Disable Logging
There are two ways to record logs in screen:
- Toggle dynamically inside a window (
Ctrl + athenH):- Press
Ctrl + athenH(uppercaseH, i.e.,Shift + h). - A message appears in the bottom-left corner:
Creating logfile "screenlog.0". - If the log file already exists,
screenappends to it (Appending to logfile "screenlog.0"). - To stop logging, press
Ctrl + athenHagain. You will seeLogfile "screenlog.0" closed.
- Press
- Start logging automatically from launch (
screen -L):- Start your session with the
-Lflag to automatically log from the moment the session opens:1screen -L -S deploy-job - (On GNU
screen4.5.1+, you can also specify a custom filename withscreen -L -Logfile custom.log -S deploy-job.)
- Start your session with the
Where to Find the Logs
By default, screen writes log files into the directory where you originally started the screen session (not necessarily the directory you cd into later inside the shell).
Each window inside a screen session gets its own separate log file named screenlog.<N>, where <N> matches the window number:
Window in screen |
Default Log Filename | Notes |
|---|---|---|
Window 0 (first window created) |
./screenlog.0 |
Created when logging is enabled on Window 0 |
Window 1 (second window) |
./screenlog.1 |
Created when logging is enabled on Window 1 |
Window 2 (third window) |
./screenlog.2 |
Created when logging is enabled on Window 2 |
Note: When you toggle logging with
Ctrl + athenH, it only enables or disables logging for the currently active window. For example, pressingCtrl + athenHinside Window2createsscreenlog.2without logging Window0or Window1. You can check which window number you are in at any time withCtrl + athenworCtrl + athen".
Reading & Cleaning Up Log Files (Handling Escape Sequences)
Because screen captures raw terminal output, screenlog.0 includes ANSI escape sequences (used for terminal colors, cursor movements, and prompt formatting). If you open screenlog.0 in a standard text editor, you may see garbled control codes like ^[[01;32m.
- View cleanly in the terminal: Use
catorless -Rso the terminal renders the escape sequences as normal colors:1 2 3cat screenlog.0 # or page through with color support: less -R screenlog.0 - Strip escape codes for plain-text editors: Use
sed(or add an alias in~/.bashrc) to remove ANSI escape sequences and save a clean.txtfile:1 2alias stresc='sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"' stresc screenlog.0 > screenlog.0.txt
5. Screen Configuration (.screenrc) & Screen Lock
By default, screen launches with a copyright splash screen, a small scrollback buffer, and no visual indicator showing that you are inside a screen session. You can customize screen globally for your user account by creating or editing ~/.screenrc ($HOME/.screenrc), or by passing a custom config file with screen -c /path/to/file.
Recommended ~/.screenrc Options for Beginners
Create or edit ~/.screenrc and add the following settings:
|
|
What these options do:
startup_message off: Skips the initial welcome page when you runscreen.defscrollback 10000: Keeps 10,000 lines of scrollback history per window when you use Copy/Scrollback mode (Ctrl + athen[).defutf8 on: Ensures non-ASCII characters (like Chinese/Japanese/UTF-8 symbols) render properly without needing the-Uflag.autodetach on: Ensures your running tasks are automatically detached into the background if your connection drops.hardstatus alwayslastline: Adds a persistent bottom bar showing all your open window numbers and names, highlighting the active window in parentheses(0*bash), along with the server hostname and time.
Locking Your screen Terminal & Setting a Session Password
Quick Terminal Lock (Ctrl + a then x)
If you need to step away from your desk while connected to a server inside screen, you can lock the screen terminal without detaching:
- Press
Ctrl + athenx. screenwill lock the display. To unlock it, type your Linux user account password and pressEnter.
Adding a Dedicated screen Password in ~/.screenrc
Beyond the quick screen lock, you can also configure a dedicated screen password in ~/.screenrc. When configured, screen will require this password every time you re-attach to a detached session (screen -r), and will ask for both your Linux system password and your screen password when unlocking Ctrl + a then x.
- Generate an encrypted password hash using
mkpasswd(oropenssl passwd -crypt):Example output:1mkpasswd your_secret_password1iIPFln8hvJZ6c - Add the
passworddirective to~/.screenrc:1password iIPFln8hvJZ6c - Next time you detach and run
screen -r,screenwill prompt for yourscreenpassword before re-attaching. (To remove password protection later, delete thepasswordline from~/.screenrcor setpassword none.)
6. Quick Reference Cheat Sheet
| Task | Command / Shortcut |
|---|---|
| Start a named session | screen -S <name> |
| Start with custom config / UTF-8 / Logging | screen -c <file> / screen -U / screen -L |
| List active sessions | screen -ls |
| Re-attach to a session | screen -r <name> |
| Force detach & re-attach | screen -d -r <name> |
| Clean up dead sessions | screen -wipe |
| Detach from current session | Ctrl + a then d |
| Create / Rename a shell window | Ctrl + a then c / Ctrl + a then A |
| Switch windows (Next / Prev / Menu) | Ctrl + a then n / p / " |
| Split screen (Upper/Lower or Left/Right) | Ctrl + a then S / Ctrl + a then | |
| Switch between split panes | Ctrl + a then Tab |
| Close current pane / Close all other panes | Ctrl + a then X / Ctrl + a then Q |
| Scrollback / Copy mode & Paste | Ctrl + a then [ (copy with Space, paste with Ctrl + a ]) |
Toggle logging for current window (screenlog.<N>) |
Ctrl + a then H |
Lock screen terminal |
Ctrl + a then x |
| Show system time & load | Ctrl + a then t |
| Kill current window | Ctrl + a then k |
Show help inside screen |
Ctrl + a then ? |