How to Use the Command 'screen' (with Examples)

How to Use the Command 'screen' (with Examples)

The screen command is a powerful terminal multiplexer that allows users to manage multiple shell sessions from a single SSH connection. It is especially useful for remotely accessing servers where maintaining persistent sessions is crucial. The screen utility supports various operations, including creating named sessions, logging output, and managing open sessions. It’s an essential tool for system administrators and developers working on remote servers. Moreover, alternatives like tmux and zellij offer similar functionalities, but screen remains a popular choice for its straightforward usage and rich feature set.

Start a New Screen Session

Code:

screen

Motivation:
Starting a new screen session is the foundational step when using the screen command. It allows you to open a terminal session that can persist even after your remote SSH connection is closed. This is particularly beneficial if you’re running long tasks on a server and want to ensure they continue even if you lose the connection.

Explanation:
When you simply type screen, it initiates a new screen session with a default name. This opens a new shell in which you can run your commands. If your connection drops, you can later reattach to this session without interrupting the session’s activities.

Example Output:
Upon executing the command, you’ll finding yourself in a normal terminal shell with no immediate output to indicate that you’re inside a screen session. However, the session ID will display at the bottom once you initially enter it.

Start a New Named Screen Session

Code:

screen -S session_name

Motivation:
Naming your screen sessions provides a structured way to manage multiple sessions. Utilizing descriptive session names improves usability, particularly when juggling several concurrent sessions, as it simplifies identifying and reattaching to the right session.

Explanation:
The -S flag allows you to assign a specific name to your session. Replace session_name with a relevant name that makes it easy to keep track of its purposeful activity, e.g., backup_process or dev_server.

Example Output:
Similar to starting a session without a name, you won’t get visible output. However, informative session naming can be confirmed while listing open sessions, differentiating from unnamed sessions for easier management.

Start a New Daemon and Log Output

Code:

screen -dmLS session_name command

Motivation:
There are scenarios where you want to execute a command in the background without attaching to it immediately, and you want to log the output for later review. This setup is ideal for running scripts or processes that need persistent logging for post-analysis.

Explanation:

  • -d runs the screen in “detached” mode, so you don’t directly interact with it initially.
  • -m forces the creation of a new session even if there are existing reattachable sessions.
  • -L enables logging of the output to files named screenlog.x, where x is an incremental number.
  • -S session_name names the session for convenience.
  • command is any command you wish to run in this detached session, for example, ./run_report.sh.

Example Output:
No direct output will be seen at the terminal since the command launches in the background. Logfiles screenlog.x will be generated with your command’s resulting output.

Show Open Screen Sessions

Code:

screen -ls

Motivation:
Viewing a list of all active screen sessions provides an overview of your workflows. This command is essential to locate session names or IDs for reattachment or closure, especially when operating multiple terminal sessions simultaneously.

Explanation:
The -ls option lists all screen sessions currently running. Each entry in the list will include the session ID, session name (if given), and its status (attached, detached).

Example Output:

There are screens on:
	4567.backup_process	(Detached)
	1234.dev_server		(Detached)
2 Sockets in /var/run/screen/S-user.

Reattach to an Open Screen

Code:

screen -r session_name

Motivation:
Reattaching to existing screen sessions is crucial for session continuity, allowing users to resume work on long-running tasks without interruption. This option is invaluable in cases such as recovering mid-process downloads or monitoring logs.

Explanation:
The -r flag reattaches you to a specific session. Here, session_name should match the desired session’s name which you intend to reenter, or the session ID if it lacks a name.

Example Output:
Upon execution, the terminal switches to the session’s screen, showing the running processes or data as viewed at the session’s suspension moment.

Detach from Inside a Screen

Code:

<Ctrl> + A, D

Motivation:
Detaching from a screen session without termination allows you to return to the main terminal or create and manage other sessions seamlessly. This function is vital for multitasking or preliminary session separation before disconnection.

Explanation:
This is a keyboard shortcut where <Ctrl> + A instructs the screen to interpret the next keystroke as a command, and D stands for ‘detach’. This combination isolates the console session, making it rejoinable later.

Example Output:
The display returns to the original terminal, displaying a confirmation message like [detached].

Kill the Current Screen Session

Code:

<Ctrl> + A, K

Motivation:
Sometimes, it’s necessary to terminate a session that is either concluded or malfunctioning. Closing superfluous screens helps conserve system resources and maintain organization.

Explanation:
Within a screen, <Ctrl> + A again prepares the next keystroke as a special command, with K representing ‘kill’. Be cautious, as this command dismisses the active session permanently.

Example Output:
You will receive a warning asking for confirmation. Confirmation results in the session’s closure, with no further output.

Kill a Detached Screen

Code:

screen -X -S session_name quit

Motivation:
Occasionally, sessions are detached without direct terminal control, requiring closure utilizing a command. This option is convenient for administrative cleanup of superfluous or abandoned sessions.

Explanation:

  • -X executes a command across the named screen session.
  • -S session_name specifies which session to impact.
  • quit finalizes the closure of this background session.

Example Output:
The target session is terminated discreetly, providing no feedback unless errors exist, signified during subsequent screen -ls checks for remaining live sessions.

Conclusion

Using screen effectively enables maintaining robust, persistent terminal sessions on remote systems, a core tool for efficient server management and multitasking. Understanding each function’s implication enhances your control over complex operations, whether viewing logs from a detached mode or killing errant processes gracefully. With a multitude of options available, fine-tuning workflows with screen can significantly impact your system administration and development efficiency.

Related Posts

Mastering the Command 'git tag' (with Examples)

Mastering the Command 'git tag' (with Examples)

In the world of Git, tags serve as a means to mark specific points in the repository’s history.

Read More
How to use the command 'rtmpdump' (with examples)

How to use the command 'rtmpdump' (with examples)

RTMPDump is a powerful command-line tool for downloading media content that is streamed over the Real Time Messaging Protocol (RTMP).

Read More
How to use the command 'psysh' (with examples)

How to use the command 'psysh' (with examples)

PsySH is a runtime developer console, interactive debugger, and read-eval-print loop (REPL) for PHP.

Read More