Is production: true
#linux #terminal #screen

How to Use Linux Screen: A Practical Guide for Beginners

Created: 17 Nov 2026 Modified: 17 Nov 2026 Lang: English Other languages: 中文

A practical beginner's guide to installing and using the GNU screen command to keep remote SSH tasks running, manage sessions, split terminal panes, and configure .screenrc.



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:

  1. Keep programs running in the background even after you disconnect from SSH.
  2. Run multiple interactive shells inside a single terminal connection.
  3. 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:

1
screen --version

If it is not installed, install it with your distribution’s package manager:

Debian / Ubuntu:

1
2
sudo apt-get update
sudo apt-get install screen

RHEL / CentOS / AlmaLinux / Rocky Linux / Fedora:

1
2
3
4
5
# Modern RHEL-based systems
sudo dnf install screen

# Older CentOS / RHEL systems
sudo yum install screen

2. General Usage Structure: How screen Works

Before memorizing commands, it helps to understand the three-layer mental model of screen:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
+-------------------------------------------------------------------+
|  Screen Session (e.g., "20451.my-work")                           |
|  Runs in the background on the server; survives SSH disconnects   |
|                                                                   |
|  Windows (Virtual Tabs inside the Session):                       |
|  [ Window 0: bash ]   [ Window 1: logs ]   [ Window 2: htop ]     |
|                                                                   |
|  Regions / Split Panes (How your screen is divided):              |
|  +-------------------------------------------------------------+  |
|  | Upper Region  --> displaying Window 0 (running a script)    |  |
|  +-------------------------------------------------------------+  |
|  | Lower Region  --> displaying Window 1 (watching log output) |  |
|  +-------------------------------------------------------------+  |
+-------------------------------------------------------------------+
  1. Session: A persistent workspace managed by screen in the background. You can detach from a session (leave it running) and re-attach to it later.
  2. Window: Inside a single session, you can create multiple independent shell instances (like browser tabs), numbered 0, 1, 2, etc.
  3. 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 + a then ? opens the built-in help screen (press Space or Enter to exit help).
  • Need to send a literal Ctrl + a to the shell? (e.g., to jump to the beginning of a line in bash): press Ctrl + a then a.
  • Note: Case matters! Ctrl + a then s is different from Ctrl + a then S (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:

1
2
3
4
5
# Start a named session (recommended)
screen -S download-job

# Or start an unnamed session
screen

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 + a then d.

You will return to your original shell and see a message like:

1
[detached from 20451.download-job]

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:

1
screen -ls

Example output:

1
2
3
4
There are screens on:
        20451.download-job   (Detached)
        20393.db-backup      (Detached)
2 Sockets in /var/run/screen/S-user.

To re-attach (switch into) a session:

  • If you only have one session running:
    1
    
    screen -r
    
  • If you have multiple sessions, specify the session name, PID, or a unique prefix:
    1
    2
    3
    
    screen -r download-job
    # or by PID prefix:
    screen -r 20451
    
  • To switch between two different sessions: Detach from your current session first (Ctrl + a then d), 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:
    1
    
    screen -d -r download-job
    
  • Re-attach to the most recent session or create one (-R):
    1
    
    screen -R
    
  • Clean up dead sessions (-wipe): If a session crashed or was killed uncleanly and shows up as (Dead ???) in screen -ls, remove the leftover socket files with:
    1
    
    screen -wipe
    

Kill / Terminate a Session

Once your work is done, you can close the session in several ways:

  1. Graceful exit (Recommended): Type exit (or press Ctrl + d) in every shell window inside the session. When the last window closes, you will see [screen is terminating].
  2. Force kill current window/session from inside: Press Ctrl + a then k, and press y to confirm.
  3. Terminate an entire session and all its windows from inside: Press Ctrl + a then \, and press y to confirm.
  4. Kill a session from outside (normal shell):
    1
    
    screen -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 + a then A): Once you have 3 or 4 windows open, seeing 0 bash, 1 bash, 2 bash in the window picker (Ctrl + a then ") gets confusing. Press Ctrl + a then A (uppercase A), backspace out bash, and type a descriptive title like api-server or tail-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

  1. Press Ctrl + a then S (uppercase S) to split the screen horizontally into an upper and lower region.
  2. Press Ctrl + a then Tab to move your cursor focus into the empty lower region.
  3. Press Ctrl + a then c to start a new shell in that lower region (or press Ctrl + a then " 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:

  1. Press Ctrl + a then [ (or Ctrl + a then Esc). You are now in Copy Mode.
  2. Navigate / Scroll: Use the Up / Down arrow keys, PageUp / PageDown, or Ctrl + u / Ctrl + d to scroll up and down through terminal output.
  3. Search text: Press / (search forward) or ? (search backward), type your search term, and press Enter.
  4. 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 press Space again to copy it to screen’s internal clipboard.
  5. Paste text: Inside any window in the same screen session, press Ctrl + a then ] to paste the copied text.
  6. Exit Scroll Mode: Press Esc (or q) 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:

  1. Toggle dynamically inside a window (Ctrl + a then H):
    • Press Ctrl + a then H (uppercase H, i.e., Shift + h).
    • A message appears in the bottom-left corner: Creating logfile "screenlog.0".
    • If the log file already exists, screen appends to it (Appending to logfile "screenlog.0").
    • To stop logging, press Ctrl + a then H again. You will see Logfile "screenlog.0" closed.
  2. Start logging automatically from launch (screen -L):
    • Start your session with the -L flag to automatically log from the moment the session opens:
      1
      
      screen -L -S deploy-job
      
    • (On GNU screen 4.5.1+, you can also specify a custom filename with screen -L -Logfile custom.log -S deploy-job.)

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 + a then H, it only enables or disables logging for the currently active window. For example, pressing Ctrl + a then H inside Window 2 creates screenlog.2 without logging Window 0 or Window 1. You can check which window number you are in at any time with Ctrl + a then w or Ctrl + a then ".

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 cat or less -R so the terminal renders the escape sequences as normal colors:
    1
    2
    3
    
    cat 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 .txt file:
    1
    2
    
    alias 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.

Create or edit ~/.screenrc and add the following settings:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
# 1. Disable the copyright startup splash screen
startup_message off

# 2. Increase the scrollback history buffer (default is only 100 lines)
defscrollback 10000

# 3. Enable UTF-8 encoding by default (equivalent to running `screen -U`)
defutf8 on

# 4. Use visual bell instead of audible terminal beep
vbell on

# 5. Automatically detach the session if the SSH terminal hangs up unexpectedly
autodetach on

# 6. Always show a status bar at the bottom listing hostname, open windows, and clock
hardstatus alwayslastline
hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B} %Y-%m-%d %{W}%c %{g}]'

What these options do:

  • startup_message off: Skips the initial welcome page when you run screen.
  • defscrollback 10000: Keeps 10,000 lines of scrollback history per window when you use Copy/Scrollback mode (Ctrl + a then [).
  • defutf8 on: Ensures non-ASCII characters (like Chinese/Japanese/UTF-8 symbols) render properly without needing the -U flag.
  • 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 + a then x.
  • screen will lock the display. To unlock it, type your Linux user account password and press Enter.

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.

  1. Generate an encrypted password hash using mkpasswd (or openssl passwd -crypt):
    1
    
    mkpasswd your_secret_password
    
    Example output:
    1
    
    iIPFln8hvJZ6c
    
  2. Add the password directive to ~/.screenrc:
    1
    
    password iIPFln8hvJZ6c
    
  3. Next time you detach and run screen -r, screen will prompt for your screen password before re-attaching. (To remove password protection later, delete the password line from ~/.screenrc or set password 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 ?

References