What is the screen command and how to use it?

Managing multiple terminal sessions efficiently is crucial for system administrators, developers, and anyone working extensively with remote servers. Whether you’re running long-running processes, managing multiple SSH connections, or need to maintain persistent terminal sessions, the screen command provides the essential functionality you need.

This comprehensive guide walks you through everything about the Linux screen command, from basic installation to advanced usage scenarios, helping you master terminal multiplexing for improved productivity.

Quick Summary: The screen command is a terminal multiplexer that allows you to run multiple terminal sessions within a single window, detach from sessions while keeping processes running, and reattach to sessions later from any location.

What is the Screen Command?

Screen is a full-screen window manager that multiplexes a physical terminal between several processes, typically interactive shells. Originally developed in 1987, screen remains one of the most reliable tools for managing terminal sessions in Unix-like operating systems.

The screen utility solves several common problems faced by system administrators and developers:

  • Session persistence – Keep processes running even when disconnected from SSH
  • Multiple windows – Run several programs simultaneously in one terminal
  • Session sharing – Allow multiple users to attach to the same session
  • Remote management – Maintain control over long-running tasks on remote servers

When you start a screen session, you create a virtual terminal that continues running independently of your connection status. This means you can start a lengthy compilation, database migration, or backup process, disconnect from the server, and return hours or days later to find your process still running exactly as you left it.

Why Use Screen Instead of Standard Terminal?

Consider these common scenarios where screen becomes indispensable:

  • Running a deployment script that takes hours to complete
  • Monitoring log files continuously on a remote server
  • Managing multiple services that require separate terminal windows
  • Working on unstable network connections where SSH might disconnect
  • Collaborating with team members on server configurations

Installing Screen on Linux

Most Linux distributions don’t include screen by default, but installation is straightforward using your distribution’s package manager.

Ubuntu and Debian Systems

For Ubuntu, Debian, and other Debian-based distributions, use the apt package manager:

sudo apt update
sudo apt install screen

The update command refreshes your package list, ensuring you install the latest available version.

Red Hat, CentOS, and Fedora Systems

Red Hat-based distributions use either dnf (newer systems) or yum (older systems):

# For Fedora 22 and later, CentOS 8+, RHEL 8+
sudo dnf install screen

# For older versions
sudo yum install screen

AlmaLinux and Rocky Linux

These CentOS alternatives use the same package manager:

sudo dnf install screen

openSUSE Systems

openSUSE and SUSE Linux Enterprise use zypper:

sudo zypper install screen

Arch Linux Systems

Arch Linux and derivatives use pacman:

sudo pacman -S screen

Verifying Installation

After installation, verify that screen is properly installed and check its version:

screen -v

You should see output similar to: “Screen version 4.08.00 (GNU) 05-Feb-20”

Pro Tip: If you work with remote servers frequently, install screen immediately after setting up a new server. This habit will save you from lost work when connections drop unexpectedly.

Basic Screen Commands and Usage

Understanding the fundamental screen commands allows you to start leveraging its power immediately.

Starting Your First Screen Session

Launch a new screen session by simply typing:

screen

This creates a new screen session and displays a brief license message. Press Space or Enter to continue, and you’ll find yourself in what appears to be a normal terminal. However, you’re now working inside a screen session that can be detached and reattached.

Creating Named Sessions

For better organization, especially when managing multiple sessions, create named sessions:

screen -S mysession

Replace “mysession” with a descriptive name like “deployment”, “monitoring”, or “database-backup”. Named sessions make it much easier to identify and reattach to specific sessions later.

Detaching from a Session

The most powerful feature of screen is the ability to detach from a running session. Press:

Ctrl-a d

This key combination (hold Ctrl, press ‘a’, release both, then press ‘d’) detaches you from the session while leaving all processes running in the background. You’ll return to your original terminal, but the screen session continues executing everything you started.

Listing Active Sessions

To see all currently running screen sessions:

screen -ls

This displays a list showing session IDs, creation times, and attachment status. Output looks like:

There are screens on:
    12345.mysession    (Detached)
    67890.pts-1.server (Attached)
2 Sockets in /run/screen/S-username.

Reattaching to Sessions

Reconnect to a detached session using its name or ID:

# Using session name
screen -r mysession

# Using session ID
screen -r 12345

If you only have one detached session, simply use:

screen -r

Terminating a Session

To completely end a screen session, you have two options:

# From within the session, type:
exit

# Or press:
Ctrl-d

This closes the session and terminates all processes running within it.


Managing Multiple Windows

Screen’s window management capabilities allow you to run multiple programs simultaneously within a single session.

Creating New Windows

While inside a screen session, create additional windows:

Ctrl-a c

This creates a new window and switches to it immediately. You can create as many windows as needed, each running independent processes.

Screen provides several methods to switch between windows:

# Move to next window
Ctrl-a n

# Move to previous window
Ctrl-a p

# Switch to window by number (0-9)
Ctrl-a 0  # Goes to window 0
Ctrl-a 1  # Goes to window 1

# Display window list and select
Ctrl-a "

The window list (Ctrl-a “) displays all windows with their numbers and current processes, allowing you to select the desired window with arrow keys and Enter.

Viewing Window List

To see a quick list of all windows in the status line:

Ctrl-a w

This shows a compact view like: “0$ bash 1$ htop 2-$ vim”

Closing Windows

Close the current window by exiting its shell:

exit
# or
Ctrl-d

If this was your last window, the entire screen session terminates.


Advanced Screen Features

Beyond basic session management, screen offers powerful features for complex workflows.

Split Screen Functionality

Screen allows you to split your terminal view horizontally or vertically, displaying multiple windows simultaneously.

Split the screen horizontally:

Ctrl-a S

Split the screen vertically:

Ctrl-a |

After splitting, move focus between regions:

Ctrl-a Tab

Each region can display a different window. To display content in a new region, navigate to it and switch to an existing window or create a new one.

Close the current region (but keep the window running):

Ctrl-a X

Remove all splits and return to single view:

Ctrl-a Q

Renaming Sessions and Windows

Organize your work by giving descriptive names to sessions and windows.

Rename the current window:

Ctrl-a A

The current window name appears in the status line. Type a new name and press Enter.

Scrollback Mode

Screen buffers terminal output, allowing you to scroll back and view previous output. Enter copy mode:

Ctrl-a [

Once in copy mode:
– Use arrow keys or PageUp/PageDown to scroll
– Press Enter to mark the beginning of text to copy
– Navigate to the end and press Enter again to copy
– Press Ctrl-a ] to paste copied text
– Press Escape to exit copy mode

Session Logging

Record everything that appears in your screen session to a file:

Ctrl-a H

This creates a file named “screenlog.0” (or incremented numbers for subsequent logs) in your current directory. Press Ctrl-a H again to stop logging.

Locking the Screen

Protect your screen session with a password lock when stepping away:

Ctrl-a x

This locks the terminal until you enter your system password. Your session continues running, but the screen is protected from unauthorized access.

Broadcasting to All Windows

Send the same input to all windows simultaneously:

Ctrl-a :

Then type:

at "#" stuff "your_command^M"

This sends “your_command” followed by Enter (represented by ^M) to all windows.

Advanced Tip: Create a .screenrc file in your home directory to customize screen behavior, define key bindings, and set default options that load automatically with each new session.

Practical Use Cases and Scenarios

Understanding real-world applications helps you leverage screen effectively in your daily work.

Running Long-Duration Tasks

System administrators frequently need to execute tasks that take hours or days. Screen ensures these processes continue even if your connection drops:

# Start a named session
screen -S backup

# Run your long task
rsync -avz /data/ /backup/

# Detach with Ctrl-a d
# Close your terminal or SSH connection
# Return later and reattach
screen -r backup

System Monitoring

Create a multi-window setup for comprehensive system monitoring:

# Start monitoring session
screen -S monitoring

# Window 0: System resources
htop

# Create new window (Ctrl-a c)
# Window 1: Network monitoring
iftop

# Create new window (Ctrl-a c)
# Window 2: Log monitoring
tail -f /var/log/syslog

# Navigate between windows with Ctrl-a n/p

Development Environment

Developers can organize their workflow with dedicated windows:

screen -S development

# Window 0: Code editor
vim app.py

# Window 1: Application server
python app.py

# Window 2: Database console
mysql -u root -p

# Window 3: Git operations
git status

Remote Server Management

When managing multiple servers, screen prevents losing work during network interruptions:

# SSH to remote server
ssh user@server.com

# Immediately start screen
screen -S server-work

# Your work continues even if SSH disconnects
# Upon reconnection:
ssh user@server.com
screen -r server-work

Collaborative Troubleshooting

Multiple users can attach to the same screen session for real-time collaboration:

# User 1 starts session
screen -S teamwork

# User 2 attaches to the same session
screen -x teamwork

Both users see the same screen content and can type commands, making this ideal for pair programming or collaborative debugging.


Complete Screen Command Reference

Here’s a comprehensive reference of all essential screen commands for quick access.

Session Management Commands

CommandDescription
screenStart a new screen session
screen -S nameStart a named session
screen -lsList all screen sessions
screen -r nameReattach to a detached session
screen -x nameAttach to an already attached session
screen -d nameDetach a running session
screen -X -S name quitKill a specific session

Window Management Keys

Key CombinationAction
Ctrl-a cCreate a new window
Ctrl-a nMove to next window
Ctrl-a pMove to previous window
Ctrl-a 0-9Switch to window number 0-9
Ctrl-a "Display window list
Ctrl-a wShow window bar
Ctrl-a ARename current window
Ctrl-a kKill current window

Split Screen Keys

Key CombinationAction
Ctrl-a SSplit horizontally
Ctrl-a |Split vertically
Ctrl-a TabSwitch between regions
Ctrl-a XClose current region
Ctrl-a QClose all regions except current

Other Useful Keys

Key CombinationAction
Ctrl-a dDetach from session
Ctrl-a [Enter copy/scrollback mode
Ctrl-a ]Paste copied text
Ctrl-a HToggle logging
Ctrl-a xLock terminal
Ctrl-a ?Display help screen

Customizing Screen with .screenrc

Create a configuration file to customize screen’s behavior according to your preferences.

Creating Your Configuration File

Create a .screenrc file in your home directory:

nano ~/.screenrc

Useful Configuration Options

Here are practical configuration examples:

# Disable startup message
startup_message off

# Increase scrollback buffer
defscrollback 10000

# Use 256 colors
term screen-256color

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

# Enable mouse scrolling
termcapinfo xterm* ti@:te@

# Auto-detach on hangup
autodetach on

# Visual bell instead of audio
vbell on

# Default shell
shell -$SHELL

Creating Named Windows on Startup

Automatically create and name windows when starting screen:

# Window 0: System monitoring
screen -t "Monitor" 0 htop

# Window 1: Logs
screen -t "Logs" 1

# Window 2: Work
screen -t "Work" 2

Save your .screenrc file, and these settings apply to all new screen sessions.


Troubleshooting Common Issues

Cannot Attach to Session

If you receive an error when trying to attach:

# Force detach if session is stuck
screen -d -r sessionname

# If permission denied, check socket directory
ls -la /var/run/screen/

Dead Session Won’t Disappear

Remove dead sessions from the list:

# Wipe out dead sessions
screen -wipe

Screen Commands Not Working

Verify you’re using the correct command prefix (Ctrl-a by default). If you’ve changed it in .screenrc, use that prefix instead.

Lost Screen Session

If you can’t find your session:

# List all sessions for all users (requires sudo)
sudo screen -ls

# Check for orphaned screen processes
ps aux | grep screen
Important: Screen sessions survive server reboots only if you configure them to start automatically. Normal screen sessions terminate when the system shuts down.

Screen Alternatives: tmux

While screen remains popular, tmux (terminal multiplexer) offers a modern alternative with additional features:

Key Differences

  • Configuration – tmux uses a more intuitive configuration syntax
  • Session Sharing – tmux offers better collaborative features
  • Split Panes – tmux provides more flexible pane management
  • Active Development – tmux receives more frequent updates and improvements
  • Scripting – tmux offers better scripting and automation capabilities

When to Choose Screen

Screen remains the better choice when:

  • Working on legacy systems where tmux isn’t available
  • You’re already familiar with screen’s key bindings
  • System resources are extremely limited
  • Your workflow doesn’t require advanced multiplexing features

Best Practices for Using Screen

  • Always Use Named Sessions – Make sessions identifiable with descriptive names like “deployment” or “monitoring”
  • Start Screen Immediately on SSH – Launch screen as soon as you connect to remote servers to prevent work loss
  • Keep .screenrc Minimal – Only include configurations you actually use to avoid complications
  • Document Your Sessions – Use clear window names that describe what’s running in each window
  • Regular Cleanup – Periodically check and terminate unused sessions with screen -wipe
  • Use Logging Sparingly – Enable logging only when necessary as log files can grow large quickly
  • Test Before Production – Practice screen commands on test systems before using them in critical environments
  • Combine with Other Tools – Use screen alongside tools like htop, tail, and watch for comprehensive monitoring

Conclusion

The screen command remains an essential tool in every Linux administrator’s toolkit. Its ability to maintain persistent terminal sessions, manage multiple windows efficiently, and recover from connection interruptions makes it invaluable for remote server management, long-running processes, and collaborative work.

While newer alternatives like tmux offer additional features and modern interfaces, screen’s simplicity, universal availability, and proven reliability ensure it will continue serving the Linux community for years to come. Whether you’re deploying applications, monitoring system resources, or managing remote infrastructure, mastering screen significantly improves your productivity and resilience against connection issues.

By understanding the commands and techniques covered in this guide, you can leverage screen to create robust workflows that survive network interruptions, organize complex tasks across multiple windows, and maintain control over critical processes regardless of your connection status. Start incorporating screen into your daily workflow, and you’ll quickly wonder how you ever managed without it.



You May Also Like