How to Terminate a Specific GNU Screen Session by Name in Ubuntu (Without Killing All Screens)


2 views

When managing multiple GNU Screen sessions on an Ubuntu server, administrators often need to terminate individual sessions without affecting others. The standard screen -X quit command terminates all sessions, which isn't ideal for targeted process management.

To kill a specific screen session by name while keeping others running:

screen -S session_name -X quit

For example, to terminate only "screen1" from your setup:

screen -S screen1 -X quit

This sends the quit command directly to the specified session without attaching to it.

In bash scripts where interactive commands aren't feasible, use this pattern:

#!/bin/bash
TARGET_SCREEN="screen1"
screen -S "$TARGET_SCREEN" -X quit || echo "Failed to terminate $TARGET_SCREEN"

For environments where screen names might change:

# Kill by PID (get PID from screen -ls)
screen -X -S [session_pid] quit

# Forceful termination when normal quit fails
screen -S problem_session -X stuff $'\\003'  # Sends Ctrl+C
screen -S problem_session -X quit

Always verify the session was terminated:

screen -ls | grep -q "screen1" || echo "Termination successful"
  • Permission issues when running as different users
  • Session naming conflicts
  • Background processes keeping sessions alive

For persistent sessions, consider adding kill commands for any child processes before terminating the screen.




When managing multiple screen sessions on a Linux server, you might need to terminate a specific session while keeping others running. The common approach of using screen -r followed by manual termination isn't suitable for automation scripts.


To programmatically kill a specific screen session by name, use this command:

screen -X -S "session_name" quit



Here's how you would implement this in your bash script for the example you provided:


#!/bin/bash
# Terminate screen1 while leaving screen2 running
screen -X -S "screen1" quit



For a more robust script implementation:


#!/bin/bash
SESSION_NAME="screen1"

if screen -ls | grep -q "$SESSION_NAME"; then
    screen -X -S "$SESSION_NAME" quit
    echo "Successfully terminated $SESSION_NAME"
else
    echo "Session $SESSION_NAME not found" >&2
    exit 1
fi



For systems where the screen command isn't available, you can use process IDs:


SCREEN_PID=$(screen -ls | grep "session_name" | awk -F '.' '{print $1}' | tr -d '\t')
kill $SCREEN_PID



  • Always verify the session exists before attempting to terminate it
  • Consider adding a small delay after termination for processes to clean up
  • The -X flag sends commands to a running screen session
  • The -S flag specifies which session to target
If you encounter issues:
  1. Run screen -ls to verify the session name
  2. Check for typos in the session name (they're case-sensitive)
  3. Ensure you have proper permissions to terminate the session