Website Vidya
Linux & ServersStep-by-Step Guide

How to Use Linux Screen: Manage Persistent Terminal Sessions

Learn use linux screen with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
How to Use Linux Screen: Manage Persistent Terminal Sessions
AI Executive SummaryWebsiteVidya AI

10 min read

Learn use linux screen with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What screen Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Learning how to use linux screen is an indispensable operational skill for anyone who manages remote Linux servers over SSH. Originally developed by Oliver Laumann and Carsten Bormann in 1987 as part of the GNU Project, GNU Screen is a full-screen terminal multiplexer that decouples shell sessions from physical terminal windows or network connections.

When managing remote infrastructure, network instability is a constant risk: a dropped Wi-Fi signal, VPN timeout, or accidental terminal closure instantly severs an SSH connection. Under standard shell execution, the kernel sends a SIGHUP (Hangup) signal to the controlling terminal, terminating all running child processes—potentially aborting a multi-hour database migration, compilation job, or system upgrade midway through execution.

GNU Screen eliminates this vulnerability by running as an independent background daemon that manages pseudo-terminals (PTYs). Inside Screen, tasks continue executing uninterrupted even if your SSH client disconnects. You can detach from a session on your office desktop, travel home, and reattach to the exact same running session from your laptop.

Advertisement
How to Use Linux Screen: Manage Persistent Terminal Sessions — syntax, flags, and practical terminal workflow diagram
How to Use Linux Screen: Manage Persistent Terminal Sessions — command syntax, key options, and production workflow reference.

What screen Does and When to Use It

Architecturally, GNU Screen operates using a client-server model built upon Unix pseudo-terminal master and slave pairs (/dev/ptmx and /dev/pts/*). When you launch screen, it forks a background server daemon that adopts PID 1 (init/systemd) as its parent process. The server allocates a master PTY for each virtual window, emulating a VT100/ANSI terminal and capturing input/output streams into scrollback memory buffers.

The client process connects to the server daemon through a local Unix domain socket created in /run/screen/ or /tmp/uscreens/. When an SSH session drops, only the client process terminates; the Screen server daemon detects the disconnection, closes the client socket, marks the session as 'Detached', and keeps all child processes running. Terminal control sequences are translated through the termcap/terminfo database, ensuring consistent display rendering across varying client terminal types.

At the operating system level, screen interacts with the Linux kernel networking stack through netlink sockets (AF_NETLINK), raw packet sockets, or standard POSIX resolver APIs. When running screen in cloud instances or Kubernetes worker nodes, combining flags such as -S NAME, -ls, -r [NAME], -d -r [NAME] lets you bypass slow reverse DNS lookups and inspect numeric IPv4/IPv6 addresses and socket states directly.

Availability and Installation Across Linux Distributions

The screen utility is packaged in screen across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether screen is installed and inspect which binary path and version your shell resolves:

type -a screen
screen --version 2>/dev/null || man -f screen

# Illustrative output (reviewed against documentation)
screen is /usr/bin/screen
screen (screen)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y screen

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y screen

# Arch Linux
sudo pacman -S --noconfirm screen

# Alpine Linux
sudo apk add --no-cache screen

Command Syntax, Arguments, and Exit Status Codes

screen [-opts] [cmd [args]] | screen -r [session_id]

The command-line syntax divides into session creation, listing, and resumption: screen [-S session_name] to start a new named session, screen -ls to list all active sessions, screen -r [session_name] to reattach to a detached session, and screen -d -r [session_name] to detach an active session from another terminal and reattach it locally.

Once inside a Screen session, commands are issued via a command escape key sequence: by default, press Ctrl+A followed by an action character. For example, Ctrl+A then d detaches the session, Ctrl+A then c creates a new virtual window, Ctrl+A then n switches to the next window, and Ctrl+A then [ enters copy/scrollback mode.

  • 0 — Normal command execution, clean session termination, or help displayed.
  • 1 — Operational error; no screen session found to attach, invalid option, or permission denied.
  • 127 — Command not found error, indicating that the screen package is not installed.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-S NAME--session NAMECreates a new screen session with a meaningful, human-readable name NAME.
-ls-listLists all active, detached, and attached screen sessions running on the system.
-r [NAME]--resumeReattaches to a detached screen session by name or numeric session ID.
-d -r [NAME]-d -rDetaches a session that was left attached on another terminal and reattaches it to the current terminal.
-x--multiAttaches to a non-detached session in multi-display mode (ideal for pair programming and shared monitoring).
-L--logEnables automatic real-time session logging, recording all terminal output to a screenlog.0 file.
-dmS NAME CMD-dmSStarts a command in a detached screen session immediately (ideal for automation scripts and cron jobs).
-wipe--wipeCleans up and removes dead or terminated screen sockets from the socket directory.
-X [CMD]-XSends a command directly to a running screen session from the outside shell without attaching.

Always name your sessions using screen -S descriptive-name rather than running bare screen. On servers with multiple administrative sessions, bare screen generates arbitrary numeric identifiers (such as 18420.pts-1.srv), making it impossible to identify whether a session belongs to a database migration, backup, or kernel compilation.

Advertisement

When connecting to a session from a new computer while the previous connection is still hanging, using screen -r will fail with 'There is a screen on: ... (Attached)'. Always use screen -d -r name to remotely detach the stale connection and pull the terminal session to your active window.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Start a New Named Screen Session

Launch a new terminal multiplexer session assigned a descriptive name for easy management.

screen -S backup-job

# Illustrative output (reviewed against documentation)
[screen starts a fresh terminal prompt inside session 'backup-job']

Screen clears the screen and opens a virtual shell window. All processes launched in this window are protected from SSH disconnections.

2. Detach from an Active Session Safely

Detach from a running screen session, leaving background processes running while returning to your main shell prompt.

# Inside the screen session, press:
# Ctrl + A, then press d

# Illustrative output (reviewed against documentation)
[detached from 18420.backup-job]

The Ctrl+A d keyboard shortcut safely detaches the terminal client. The session remains active in the background.

3. List All Active and Detached Screen Sessions

View all screen sessions currently running on the server along with their attachment states.

screen -ls

# Illustrative output (reviewed against documentation)
There are screens on:
        18420.backup-job        (2026-10-22 21:30:00)   (Detached)
        19210.db-migration      (2026-10-22 21:35:12)   (Attached)
2 Sockets in /run/screen/S-admin.

The output lists session PIDs, names, creation timestamps, and states (Detached or Attached).

4. Reattach to a Detached Screen Session

Resume working inside a previously detached screen session using its name.

screen -r backup-job

# Illustrative output (reviewed against documentation)
[screen restores the terminal display and command prompt of 'backup-job']

Screen reconnects your terminal to the virtual session, restoring terminal history and running processes.

5. Launch a Detached Background Task from a Script

Start a long-running Python worker daemon in a detached screen session from a deployment script.

screen -dmS worker-task python3 /opt/services/worker.py

# Illustrative output (reviewed against documentation)
# Command executes immediately and returns to prompt while worker runs in background.

The -dmS combination creates a new session in detached mode (-d -m) and immediately executes the worker script.

6. Enable Real-Time Terminal Session Logging to File

Record all terminal output, errors, and compilation logs to a text file for post-incident auditing.

screen -L -Logfile /var/log/kernel_build.log -S build-kernel

# Illustrative output (reviewed against documentation)
[screen starts session with logging enabled to /var/log/kernel_build.log]

The -L option automatically mirrors every character printed to the terminal into the specified log file.

Real-World Workflows, Pipelines, and Shell Automation

Unattended Long-Running System Upgrade and Patching Safeguard

Ensure major distribution upgrades (such as do-release-upgrade or full distro-sync) never fail due to an interrupted SSH connection.

#!/usr/bin/env bash
set -euo pipefail

SESSION_NAME="distro-upgrade"

echo "=== Starting Protected Upgrade Session: ${SESSION_NAME} ==="

# Check if session already exists
if screen -ls | grep -q "${SESSION_NAME}"; then
  echo "Session ${SESSION_NAME} already exists! Reattaching..."
  screen -d -r "${SESSION_NAME}"
  exit 0
fi

# Launch upgrade inside a logged screen session
screen -L -Logfile "/var/log/upgrade-$(date +%Y%m%d).log" -S "${SESSION_NAME}" bash -c '
  echo "=== Running Distribution Upgrade inside GNU Screen ==="
  sudo apt-get update && sudo apt-get dist-upgrade -y
  echo "Upgrade finished successfully at $(date)."
  exec bash
'

# Illustrative output (reviewed against documentation)
=== Starting Protected Upgrade Session: distro-upgrade ===
[screen opens and executes the upgrade sequence with full logging]

This workflow encapsulates system upgrades inside a logged screen session, ensuring package installation proceeds even if the network connection drops.

Collaborative Terminal Sharing and Pair Programming Session

Allow two engineers to share a single terminal session simultaneously across different SSH connections.

# Engineer 1 starts a shared session:
screen -S pairing-session

# Engineer 2 joins the exact same session from another terminal:
screen -x pairing-session

# Illustrative output (reviewed against documentation)
[Both users see identical terminal output and can type simultaneously in real time]

The -x flag attaches to a session in multi-display mode, synchronizing screen output and keystrokes between both users.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding screen inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

Screen creates Unix domain sockets in /run/screen/S-[username] with strict permissions (0700), ensuring only the owner or root can list and attach to sessions. On multi-user systems, never change socket permissions or run screen setuid root unless multi-user ACL sharing is explicitly configured.

To lock an unattended screen session when stepping away from your physical workstation, press Ctrl+A followed by x. Screen will prompt for your Linux user password before allowing anyone to view or interact with the terminal.

GNU/Linux, BSD, and BusyBox Implementation Differences

GNU Screen is available across virtually all Unix and Linux operating systems, including Ubuntu, Debian, RHEL, Fedora, Arch, FreeBSD, OpenBSD, and macOS. However, many modern distributions default to tmux (Terminal Multiplexer) for new installations.

While tmux offers cleaner configuration files and active feature development, GNU Screen remains pre-installed on countless enterprise systems and minimal recovery environments, making Screen proficiency essential for legacy sysadmins.

Troubleshooting Common Errors and Diagnostics

There is a screen on: ... (Attached) - Cannot resume

Root Cause: The session was left attached to an earlier terminal window or an orphaned SSH connection.

Resolution: Use the -d -r options to remotely detach the old connection and reattach it locally.

screen -d -r session_name

Cannot make directory '/run/screen': Permission denied

Root Cause: The runtime socket directory /run/screen does not exist or has incorrect directory permissions.

Resolution: Recreate the socket directory with standard permissions or export SCREENDIR to an accessible directory.

sudo mkdir -p /run/screen && sudo chmod 777 /run/screen
# Or use custom directory:
export SCREENDIR=$HOME/.screen && mkdir -p $SCREENDIR

Screen session listed as '(Dead ???)' in screen -ls

Root Cause: The system was rebooted or the screen server crashed, leaving an orphaned socket file.

Resolution: Run screen -wipe to clean up dead socket references.

screen -wipe

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Press Ctrl+A followed by [ (left square bracket) to enter copy/scrollback mode. Use the arrow keys or Page Up/Down to scroll through history. Press Esc to exit scrollback mode.
Both are terminal multiplexers that preserve sessions. tmux is more modern, supports advanced window splitting, scriptable automation, and cleaner configuration. GNU Screen is older, simpler, and pre-installed on virtually every legacy enterprise server.
Inside the session, type exit or press Ctrl+D until all windows close. Screen will report '[screen is terminating]' and exit back to your main shell.
Press Ctrl+A followed by | (pipe) for vertical split, or Ctrl+A followed by S for horizontal split. Switch between regions using Ctrl+A Tab, and create a terminal in the new region using Ctrl+A c.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout