15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started
08.10.2024

The Complete Guide to GNU Screen Commands in Linux

GNU Screen is a terminal multiplexer that lets you create, manage, and persist multiple shell sessions from a single terminal window. When you detach from a Screen session, every process running inside it continues executing — surviving SSH disconnections, network drops, and terminal closures — and remains fully accessible the moment you reconnect.

For anyone managing remote servers over SSH, this single capability eliminates an entire class of operational risk: a dropped connection no longer kills a running database migration, a multi-hour compilation job, or a live log-monitoring process.

Why GNU Screen Remains Relevant in Modern Linux Administration

Tools like tmux have gained popularity, but Screen ships as a default or near-default package on virtually every enterprise Linux distribution and minimal server image. When you SSH into a bare-metal machine or a freshly provisioned VPS Hosting instance, Screen is almost always available without any additional installation. Its low memory footprint and POSIX compliance make it the pragmatic choice in constrained or locked-down environments.

Core capabilities at a glance:

  • Session persistence: Processes survive terminal disconnection, SSH timeout, and client-side crashes
  • Window multiplexing: Multiple independent shell windows inside a single session
  • Session sharing: Two users can attach to the same session simultaneously for collaborative debugging
  • Serial console access: Screen can connect directly to `/dev/ttyS*` devices for out-of-band server management
  • Scriptable startup: The `.screenrc` configuration file enables fully automated multi-window environments on launch

GNU Screen vs. tmux: Choosing the Right Multiplexer

Both tools solve the same core problem but with different design philosophies. The table below covers the distinctions that matter in production environments.

FeatureGNU Screentmux
Default availabilityPre-installed on most distrosRequires explicit installation
Configuration file`~/.screenrc``~/.tmux.conf`
Pane splitting (horizontal/vertical)Limited (vertical only via regions)Full, flexible pane splitting
Session sharingNative multi-attachNative multi-attach
Scripting / automation`screen -X` command injection`tmux send-keys`, rich API
Memory footprintVery lowLow
Serial device supportYes (`screen /dev/ttyS0`)No
Status bar customizationModerate (hardstatus)Highly flexible
Copy modevi-stylevi or emacs style
Plugin ecosystemNoneActive (TPM)
Ideal use caseMinimal servers, serial consoles, legacy envsDeveloper workstations, complex layouts

Practical guidance: On a headless Dedicated Server running long-term background jobs, Screen's simplicity and universal availability make it the lower-friction choice. For a developer who needs split panes and a rich status bar, tmux wins.

Installing GNU Screen

Screen is pre-installed on most distributions. Verify with:

“`bash

screen –version

“`

If it is absent, install it using the appropriate package manager:

Debian / Ubuntu:

“`bash

sudo apt-get update && sudo apt-get install screen

“`

CentOS / RHEL 7:

“`bash

sudo yum install screen

“`

CentOS Stream / RHEL 8+ / AlmaLinux / Rocky Linux:

“`bash

sudo dnf install screen

“`

Fedora:

“`bash

sudo dnf install screen

“`

Arch Linux:

“`bash

sudo pacman -S screen

“`

Alpine Linux (common in containers):

“`bash

apk add screen

“`

After installation, no daemon or service is required. Screen operates entirely as a user-space process.

Starting a Screen Session

Basic Session

“`bash

screen

“`

This drops you into a new session with a standard shell. The interface is indistinguishable from a normal terminal until you use Screen's command prefix.

“`bash

screen -S session_name

“`

Always name your sessions in production. Unnamed sessions are identified only by their PID, which makes reattachment error-prone when multiple sessions are running.

Naming convention tip: Use descriptive names that reflect the workload — `screen -S db-migration`, `screen -S log-monitor`, `screen -S build-php82`. This pays dividends when you return to a server after hours away.

Starting a Session and Running a Command Immediately

“`bash

screen -S backup-job bash -c 'rsync -avz /data/ user@remote:/backup/ && echo DONE'

“`

The session persists even after the command completes, allowing you to inspect the output later.

Starting a Session in Detached Mode

“`bash

screen -dmS headless-job ./long_running_script.sh

“`

The `-dm` flags create the session and immediately detach. This is the correct pattern for launching background jobs from cron or deployment scripts — the process runs inside a named, recoverable Screen session without requiring an interactive terminal.

The Command Prefix: Understanding Ctrl+A

Every Screen keyboard shortcut begins with the escape sequence `Ctrl+A`. This keystroke tells Screen that the next character is a command, not input for the running program. Understanding this model is essential before memorizing individual shortcuts.

If you run a program inside Screen that itself uses `Ctrl+A` (for example, some text editors or the `readline` library), you can send a literal `Ctrl+A` to the inner program by pressing `Ctrl+A` twice (`Ctrl+A, Ctrl+A`).

Detaching and Reattaching Sessions

Detaching from a Running Session

“`

Ctrl+A, D

“`

The session continues running in the background. You are returned to the parent shell. No processes inside the session are interrupted.

Listing All Sessions

“`bash

screen -ls

“`

Example output:

“`

There are screens on:

14231.db-migration (Detached)

14089.log-monitor (Attached)

13901.build-php82 (Detached)

3 Sockets in /var/run/screen/S-deploy.

“`

The status `Attached` means another terminal is currently connected to that session. `Detached` means it is running but no terminal is connected.

Reattaching to a Specific Session

“`bash

screen -r db-migration

“`

Or by PID:

“`bash

screen -r 14231

“`

Force-Attaching to an Already-Attached Session

If a session shows `Attached` but you need to take it over (for example, after a stale SSH connection left it locked):

“`bash

screen -d -r log-monitor

“`

The `-d` flag forcibly detaches the other connection before reattaching you. This is a critical recovery technique when a previous SSH session died without cleanly detaching.

Multi-Attach: Two Users on the Same Session

“`bash

screen -x session_name

“`

Both terminals see identical output in real time. This is invaluable for pair debugging or guided server walkthroughs with a colleague — both parties observe and can interact with the same shell.

Managing Windows Within a Session

A single Screen session can contain an unlimited number of windows. Each window is an independent shell (or process).

Creating a New Window

“`

Ctrl+A, C

“`

ShortcutAction
`Ctrl+A, N`Next window
`Ctrl+A, P`Previous window
`Ctrl+A, 0–9`Jump directly to window by number
`Ctrl+A, "`Interactive list of all windows
`Ctrl+A, '`Prompt to enter window number or name

Renaming a Window

“`

Ctrl+A, A

“`

Type the new name and press Enter. Meaningful window names are displayed in the hardstatus bar, making navigation far faster in sessions with many windows.

Closing a Window

Type `exit` or press `Ctrl+D` in the window's shell. When the last window in a session is closed, the session terminates.

Splitting the Screen into Regions

Screen supports splitting the terminal into multiple visible regions, each displaying a different window simultaneously.

Split Horizontally (top/bottom)

“`

Ctrl+A, S

“`

Split Vertically (left/right)

“`

Ctrl+A, |

“`

Note: Vertical splitting requires Screen 4.1.0 or later.

Moving Between Regions

“`

Ctrl+A, Tab

“`

Assigning a Window to a Region

After moving focus to a region, use `Ctrl+A, "` to select which window to display there.

Removing a Region

“`

Ctrl+A, X (remove current region)

Ctrl+A, Q (remove all regions except current)

“`

Important distinction: Removing a region does not close the window running inside it. The window continues running; you simply stop displaying it in that split.

Copy and Paste (Scrollback Mode)

Screen maintains a scrollback buffer for each window. To access it:

“`

Ctrl+A, [

“`

This enters copy mode. Navigation uses vi-style keys:

  • `h`, `j`, `k`, `l` — move cursor
  • `Ctrl+F` / `Ctrl+B` — page forward / backward
  • `/` — search forward
  • `?` — search backward
  • `Space` — mark start of selection
  • `Space` (again) — mark end and copy to buffer

To paste the copied text:

“`

Ctrl+A, ]

“`

The default scrollback buffer is 100 lines. For server log monitoring, increase this significantly in `.screenrc` (covered below).

Locking a Screen Session

“`

Ctrl+A, X

“`

The session locks immediately and prompts for your Unix user password before allowing access. Use this when stepping away from a terminal that is connected to a sensitive server — it is faster than closing the SSH connection and reattaching.

Sending Commands to a Session Without Attaching

The `-X` flag allows you to inject Screen commands into a running session from outside:

“`bash

screen -S db-migration -X stuff "tail -f /var/log/mysql/error.logn"

“`

The `stuff` command sends keystrokes to the active window of the named session. The `n` simulates pressing Enter. This technique is used in deployment automation scripts to interact with long-running Screen sessions without requiring human attachment.

Configuring Screen with .screenrc

The `~/.screenrc` file is read at startup and controls Screen's default behavior. A well-crafted `.screenrc` transforms Screen from a basic multiplexer into a genuinely ergonomic environment.

Create or edit it:

“`bash

nano ~/.screenrc

“`

“`bash

Disable the startup message

startup_message off

Set scrollback buffer to 10,000 lines (critical for log monitoring)

defscrollback 10000

Enable UTF-8

defutf8 on

Set default shell

shell -$SHELL

Visual bell instead of audible

vbell on

Hardstatus bar: shows hostname, window list, and current time

hardstatus on

hardstatus alwayslastline

hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B} %d/%m %{W}%c %{g}]'

Bind F2 to create a new window

bindkey -k k2 screen

Change escape key to Ctrl+B (useful if Ctrl+A conflicts with other tools)

escape ^Bb

Auto-detach on hangup signal (critical for SSH session drops)

autodetach on

Disable flow control (prevents Ctrl+S from freezing the terminal)

defflow off

“`

The `autodetach on` directive is non-negotiable for SSH use. Without it, if your SSH connection drops unexpectedly (rather than you pressing `Ctrl+A, D`), Screen may terminate the session instead of detaching it. With `autodetach on`, a SIGHUP signal (sent when SSH disconnects) triggers a clean detach rather than session termination.

`defflow off` prevents the common frustration of accidentally pressing `Ctrl+S` and appearing to freeze the terminal. Many administrators waste minutes troubleshooting a "frozen" terminal that is simply in XON/XOFF flow control pause.

Practical Production Use Cases

Running a Database Migration Safely

“`bash

screen -S db-migrate

Inside the session:

php artisan migrate –force 2>&1 | tee /var/log/migration-$(date +%F).log

Detach: Ctrl+A, D

Reattach later to check progress:

screen -r db-migrate

“`

If the SSH connection drops mid-migration, the process continues. You reattach and find it either still running or completed with full output preserved in the log and the scrollback buffer.

Monitoring Multiple Log Files Simultaneously

“`bash

screen -S monitoring

Window 0: nginx access log

tail -f /var/log/nginx/access.log

Ctrl+A, C — new window

Window 1: application error log

tail -f /var/log/app/error.log

Ctrl+A, C — new window

Window 2: system messages

journalctl -f

“`

Navigate between windows with `Ctrl+A, "` to see which log is generating activity.

Automated Deployment Script with Screen

“`bash

#!/bin/bash

screen -dmS deploy bash -c '

git pull origin main &&

composer install –no-dev &&

php artisan config:cache &&

systemctl reload php8.2-fpm &&

echo "Deployment complete at $(date)" >> /var/log/deploy.log

'

echo "Deployment started in background screen session 'deploy'"

echo "Monitor with: screen -r deploy"

“`

This pattern is especially useful on a VPS with cPanel where you may be managing multiple application deployments from a single administrative shell.

Serial Console Access

“`bash

screen /dev/ttyS0 115200

“`

Screen doubles as a serial terminal emulator. This is the standard technique for accessing the console of a physical server, network switch, or embedded device over a serial connection — without requiring minicom or picocom.

Common Pitfalls and How to Avoid Them

Nested Screen sessions: If you SSH from a Screen session on Machine A into Machine B and start Screen there, you now have two layers of `Ctrl+A` handling. The inner Screen session captures `Ctrl+A` before the outer one sees it. To send `Ctrl+A` to the outer session, press `Ctrl+A, Ctrl+A`. To avoid confusion, change the escape key of the inner session in its `.screenrc` using `escape ^Bb`.

Dead sessions not cleaning up: If Screen crashes or the host reboots uncleanly, socket files may persist in `/var/run/screen/` or `~/.screen/`, showing sessions as `Dead`. Clean them with:

“`bash

screen -wipe

“`

Session owned by root vs. user: A Screen session started as root cannot be reattached by a non-root user, and vice versa. If you `sudo su` inside a Screen session and then detach, reattach as root or via `sudo screen -r`.

`TERM` variable mismatch: Some applications inside Screen behave incorrectly because `TERM` is set to `screen` or `screen-256color` rather than `xterm-256color`. If a TUI application renders incorrectly, check with `echo $TERM` and override in `.screenrc` with `term xterm-256color` if needed.

Scrollback buffer exhaustion: The default 100-line scrollback is inadequate for any serious log monitoring. Always set `defscrollback 10000` or higher in `.screenrc` on servers used for active administration.

Quick Reference: Essential Screen Commands

ActionCommand / Shortcut
Start new session`screen`
Start named session`screen -S name`
Start detached session`screen -dmS name`
List sessions`screen -ls`
Reattach by name`screen -r name`
Force reattach`screen -d -r name`
Multi-attach`screen -x name`
Detach`Ctrl+A, D`
New window`Ctrl+A, C`
Next window`Ctrl+A, N`
Previous window`Ctrl+A, P`
Window list`Ctrl+A, "`
Rename window`Ctrl+A, A`
Split horizontal`Ctrl+A, S`
Split vertical`Ctrl+A,`
Move between regions`Ctrl+A, Tab`
Enter copy/scroll mode`Ctrl+A, [`
Paste buffer`Ctrl+A, ]`
Lock session`Ctrl+A, X`
Kill current window`Ctrl+A, K`
Kill entire session`Ctrl+A, `
Send command to session`screen -S name -X stuff "cmdn"`
Clean dead sessions`screen -wipe`

Deployment Context: Screen on Managed Hosting Environments

Screen operates at the shell level, making it compatible with any Linux environment where you have SSH access. This includes bare-metal servers, Dedicated Servers, and standard VPS Hosting instances. It is not available in shared hosting environments where SSH access is restricted or absent.

For workloads that involve persistent background processing — such as GPU-accelerated model inference, large dataset preprocessing, or long-running batch jobs — combining Screen with a GPU Hosting environment gives you both the computational resources and the session persistence required to manage multi-hour jobs reliably.

If your infrastructure includes web-facing services alongside background processing, pairing Screen-managed backend jobs with properly secured SSL Certificates on your public endpoints ensures the entire stack — both the visible application layer and the administrative backend — operates with appropriate security controls.

Decision Matrix: When to Use Screen

Use Screen when:

  • You need session persistence on a server where only Screen is available
  • You are accessing a serial console or embedded device
  • You are running a single long-duration process and do not need split panes
  • You are on a minimal Alpine or BusyBox-based system
  • You need to share a session with another administrator in real time

Consider tmux instead when:

  • You require flexible horizontal and vertical pane splitting
  • You want a plugin ecosystem for status bar enhancements
  • You are building a developer workstation environment with complex layouts
  • Your team has standardized on tmux configuration management

Use neither (use systemd or supervisor instead) when:

  • The goal is purely to run a background service that should survive reboots
  • You do not need interactive access to the running process
  • The process should restart automatically on failure

Technical Key-Takeaway Checklist

Before relying on Screen in a production environment, verify the following:

  • `autodetach on` is present in `~/.screenrc` — without it, SSH drops can kill sessions
  • `defscrollback` is set to at least 5000 lines for log-heavy workloads
  • `defflow off` is set to prevent accidental `Ctrl+S` freezes
  • All long-running sessions are named (`-S flag`) — never rely on PID-only identification
  • You know the `screen -d -r` recovery command for stale attached sessions
  • Dead session sockets are periodically cleaned with `screen -wipe`
  • If running as multiple users, you understand the root/user session ownership boundary
  • The `TERM` variable is verified if TUI applications render incorrectly inside Screen
  • For fully automated background jobs, `screen -dmS` is used rather than `nohup` or bare `&`, giving you a recoverable, inspectable session

FAQ

Does GNU Screen survive a server reboot?

No. Screen sessions are held in memory as processes. A full server reboot terminates all Screen sessions and their child processes. For processes that must survive reboots, use systemd units or a process supervisor like Supervisor. Screen is the correct tool for interactive persistence across disconnections, not across reboots.

What is the difference between `screen -r` and `screen -x`?

`screen -r` reattaches to a detached session — it fails if the session is already attached elsewhere. `screen -x` attaches to a session regardless of its current attachment state, allowing two terminals to share the same session simultaneously. Use `-x` for collaborative debugging; use `-r` for standard reattachment.

How do I scroll up inside a Screen window?

Enter copy mode with `Ctrl+A, [`, then use arrow keys, `Page Up`/`Page Down`, or vi-style navigation (`Ctrl+F`, `Ctrl+B`). Press `Escape` or `q` to exit copy mode. Ensure `defscrollback` in `.screenrc` is set high enough to retain the history you need.

Can Screen be used without root privileges?

Yes. Screen runs entirely as the invoking user. No root privileges are required to create, attach, or manage sessions. The socket files are stored in a per-user directory (typically `/var/run/screen/S-username/`). The only exception is if Screen itself is not installed — installation requires package manager access, which typically requires root or sudo.

Why does my Screen session show "Attached" when no one is connected?

This typically happens when an SSH connection dropped without sending a clean SIGHUP — for example, due to a network timeout rather than an explicit logout. The session retains its `Attached` state because Screen never received the disconnect signal. Use `screen -d -r session_name` to forcibly detach the ghost connection and reattach cleanly.

15%

Save 15% on All Hosting Services

Test your skills and get Discount on any hosting plan

Use code:

Skills
Get Started