Detach Screen From Another SSH Session

Screen is a terminal multiplexer in Linux that allows you to create multiple virtual terminal sessions within a single SSH connection. Sometimes you may need to detach or manage screen sessions that are running in other SSH connections, especially when working on shared servers or when sessions are accidentally left running.

Listing Active Screen Sessions

Before detaching any screen session, you need to identify which sessions are currently running. Use the following command to list all active screen sessions:

screen -ls

This will display output similar to:

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

The output shows the process ID, terminal, and current state (Attached/Detached) of each screen session.

Detaching Screen Sessions

Basic Detach

To detach a screen session that is currently detached, use:

screen -d session_id

For example, to detach session with process ID 12345:

screen -d 12345

Force Detach

If a screen session is currently attached (being used by another terminal), you need to force detach it using the -D flag:

screen -D 12346

Detach All Sessions

To detach all screen sessions at once:

screen -X -S . -Q quit

Reattaching to Detached Sessions

To reattach to a specific detached screen session:

screen -r session_id

If multiple sessions exist with the same name, use the full session identifier:

screen -r 12345.pts-0.server

To detach any existing attachment and then reattach:

screen -d -r session_id

Killing Screen Sessions

To completely terminate a screen session, use:

screen -S session_id -X quit

For example:

screen -S 12345 -X quit

Using Screen in Scripts

Screen can be automated in bash scripts for running background tasks:

#!/bin/bash
# Create a detached screen session running a command
screen -S backup_job -d -m rsync -av /home/ /backup/

# Later, attach to view progress
screen -r backup_job

Common Screen Commands

Command Description
screen -ls List all screen sessions
screen -d session_id Detach a session
screen -D session_id Force detach an attached session
screen -r session_id Reattach to a detached session
screen -S name -X quit Kill a screen session

Conclusion

Managing screen sessions across multiple SSH connections is essential for efficient remote server administration. The key commands are screen -ls to list sessions, screen -D to force detach, and screen -r to reattach, giving you full control over terminal multiplexing in distributed environments.

Updated on: 2026-03-17T09:01:38+05:30

586 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements