screen - Linux


Overview

The screen command in Linux is a powerful terminal multiplexer allowing users to manage multiple terminal sessions from a single window. It’s especially useful for remote session management, as it enables sessions to persist even when the connection is interrupted. Users can detach and reattach to these sessions without losing any running processes. This functionality makes screen ideal for long-running tasks on remote servers, multitasking, and collaborative workflows.

Syntax

The basic syntax for the screen command is:

screen [options] [command [args]]
  • options: Modifiers that change how screen behaves.
  • command: An optional command that screen will execute in the new window.
  • args: Arguments for the command.

Options/Flags

  • -S name: Starts a new session with a specified name, making it easier to reattach later.
  • -ls or -list: Lists all running screen sessions.
  • -r [session]: Reattaches to a detached screen session. If there are multiple sessions, specify which one by name or PID.
  • -d: Detaches a screen session. It can be combined with -r to detach a session elsewhere and reattach it here.
  • -X command: Executes a screen command, such as quit.
  • -D -RR: Effectively reattaches a session and if necessary, detaches or even creates it first.
  • -v: Displays version information.

Examples

  1. Starting a New Named Screen Session

    screen -S mysession
    

    Starts a new screen session named “mysession”.

  2. Listing All Sessions

    screen -ls
    

    Lists all active screen sessions.

  3. Detaching from a Session
    Press Ctrl-a followed by d.

  4. Reattaching to a Specific Session

    screen -r mysession
    

    Reattaches to the session named “mysession”.

  5. Running a Long-Running Process

    screen -S longrun
    

    Start a session and run a process like a web server or a script that takes a long time to finish.

Common Issues

  • Trouble Reattaching: Ensure the exact name or PID of the session is specified if multiple sessions are running.
  • Cannot See Output Immediately: Try pressing Ctrl-a followed by Esc to enter copy mode, then scroll to see the buffer.
  • Errors About Unknown Terminal: Ensure your $TERM setting is correct or try using a basic setting like xterm.

Integration

The screen command can be integrated with SSH for managing remote sessions or combined with Bash scripts for automating repetitive tasks in robust environments.

Example Script:

#!/bin/bash
# Starts multiple screen sessions for different tasks
screen -dmS session1 ./script1.sh
screen -dmS session2 ./script2.sh
screen -list
  • tmux: Another terminal multiplexer with similar functionalities but different command syntax and enhanced features.
  • byobu: An enhancement for screen and tmux that provides easy to use interface and pre-configured settings.

For further reading and more detailed information, consult the official GNU Screen documentation: GNU Screen Manual.