How to Keep GNU Screen Session Alive After Command Termination


4 views

When running commands in GNU Screen with screen [command], the session automatically terminates after command completion. This behavior becomes problematic when you need to:

  • Examine command output after execution
  • Run long-running maintenance commands (like fsck)
  • Keep logs accessible post-execution

For existing running sessions, use these Screen commands:

# Method 1: Set zombie attribute (Ctrl-a then :)
zombie [process group]

# Method 2: Prevent termination (Ctrl-a then :)
deattach on

Add to your ~/.screenrc:

# Keep window open after command exits
zombie kr

# Alternative: Prevent automatic termination
autodetach on

To properly run filesystem checks:

# Start screen with keep-alive option
screen -S fsck_session -dm bash -c 'fsck /dev/sda1; exec bash'

# Later reattach to see output
screen -r fsck_session

This pattern works well for most commands:

screen -S maintenance -dm bash -c 'your_command; exec bash'

For complex workflows:

screen -S work_session
# Create new window (Ctrl-a c)
# Run your command
# Set zombie attribute (Ctrl-a : zombie kr)
# Continue working in other windows

If sessions still terminate unexpectedly:

# Check screen version
screen -v

# Verify .screenrc loading
screen -L -S debug_session

When running commands in GNU Screen like screen fsck /dev/sda1, the session terminates immediately after command completion with the message [screen is terminating]. This behavior prevents you from reviewing command output or maintaining persistent sessions.

By default, Screen treats the initial command as the session's "main process." When this process exits, Screen assumes the session should terminate. This is problematic for:

  • Diagnostic commands (fsck, memtest)
  • Long-running scripts
  • Output inspection needs

If you already have a Screen session running:

# Press Ctrl+a then : to enter command mode
screen -X stuff "exec bash^M"  # For existing session, adds new shell process

Or alternatively:

Ctrl+a : multiuser on
Ctrl+a : acladd username  # Allows session to persist

When starting new sessions, use these approaches:

# Method 1: Nested shell
screen -S fsck_session bash -c "fsck /dev/sda1; exec bash"

# Method 2: Detach immediately
screen -dmS persistent_session fsck /dev/sda1
screen -r persistent_session  # Reattach later

Add these to your ~/.screenrc for permanent solutions:

# Keep window open after command exits
shell -$SHELL

# Auto-spawn new shell on exit
screen -t "$STY" $SHELL -c 'your_command; $SHELL'

For a filesystem check that might need review:

screen -S fsck_scan -L -Logfile fsck.log bash -c "fsck -fy /dev/sda1; echo 'Press Enter'; read line"

This combination:

  • Names the session (-S)
  • Logs output (-L)
  • Keeps terminal open (read)
  • Allows reattachment