In the world of remote development and system administration, maintaining persistent sessions across SSH connections is crucial. Whether you’re running Claude Code for long AI-assisted coding sessions, managing servers, or simply want to pick up exactly where you left off after commuting from work to home, GNU Screen is your indispensable companion.
Table of Contents
- Why Screen Matters
- Getting Started with Screen
- Named Sessions: Your Workflow Organizer
- Seamless Location Switching
- Advanced Screen Features
- Screen with Development Tools
- Automating Your Screen Workflow
- Troubleshooting Common Issues
- Best Practices and Tips
Why Screen Matters
Imagine this scenario: You’re deep into a complex debugging session using Claude Code at work. Multiple files are open, you’re in the middle of a git rebase, and you’ve got several background processes monitoring logs. Suddenly, it’s time to head home. Without Screen, you’d lose everything. With Screen, you simply detach, go home, SSH back in, and continue exactly where you left off.
Key Benefits
- Session Persistence: Survives network disconnections, SSH timeouts, and terminal closures
- Multi-tasking: Run multiple windows within a single SSH connection
- Session Sharing: Collaborate by sharing screens with team members
- Background Processing: Keep long-running tasks alive without maintaining connection
- Organization: Name and organize sessions by project or task
Getting Started with Screen
Installation
# Ubuntu/Debian
sudo apt-get install screen
# CentOS/RHEL/Fedora
sudo yum install screen
# macOS (with Homebrew)
brew install screen
# Check installation
screen --version
Basic Commands
# Start a new screen session
screen
# Start with a name
screen -S my-session
# List all sessions
screen -ls
# Attach to a session
screen -r session-name
# Detach from current session
# Press: Ctrl+A, then D
Named Sessions: Your Workflow Organizer
One of Screen’s most powerful features is the ability to name sessions. This transforms screen from a simple terminal multiplexer into a sophisticated project management tool.
Creating Named Sessions
# Basic naming
screen -S project-alpha
# Using current directory as session name
screen -S "$(basename "$PWD")"
# With timestamp
screen -S "$(basename "$PWD")-$(date +%Y%m%d)"
# Project-specific naming
screen -S "claude-code-session"
screen -S "wordpress-maintenance"
screen -S "data-analysis"
Automatic Directory-Based Naming
Create this handy function in your ~/.bashrc
or ~/.zshrc
:
# Function to create screen session named after current directory
function sscreen() {
local session_name="${1:-$(basename "$PWD")}"
# Check if session already exists
if screen -list | grep -q "\.${session_name}\s"; then
echo "Attaching to existing session: $session_name"
screen -r "$session_name"
else
echo "Creating new session: $session_name"
screen -S "$session_name"
fi
}
# Alias for quick access
alias ss='sscreen'
Now you can simply type ss
in any directory to create or attach to a session named after that directory.
Seamless Location Switching
This is where Screen truly shines. Here’s how to maintain session continuity when switching between different locations or devices:
Starting a Session (From Any Location)
# SSH into your development server
ssh user@dev-server
# Create a session for your current project
cd ~/projects/ai-assistant
screen -S ai-assistant
# Start your development environment
claude-code .
# Or any other interactive tool
vim main.py
Switching Locations (The Reality: Just Close and Go!)
Here’s the beautiful part: You don’t need to manually detach! When properly configured, Screen automatically handles disconnections. Just close your laptop lid and go.
# What happens when you close the lid:
# 1. Your SSH connection drops
# 2. Screen detects the disconnection
# 3. Your session automatically detaches
# 4. All your work continues running on the server
Resuming From Another Location
# SSH back into your server
ssh user@dev-server
# List your sessions
screen -ls
# Output:
# There is a screen on:
# 12345.ai-assistant (Attached) # Shows as Attached until cleaned up
# or
# 12345.ai-assistant (Detached) # After automatic cleanup
# Reattach to your session
screen -r ai-assistant
# Or if it still shows as attached:
screen -dr ai-assistant # Force detach and reattach
# You're back exactly where you left off!
Automatic Detachment: Set It and Forget It
The magic of Screen is that it handles disconnections gracefully by default. However, you can optimize this behavior:
Screen Configuration for Automatic Handling
Add to your ~/.screenrc
:
# Automatically detach on hangup
autodetach on
# Don't display the copyright page
startup_message off
# Detach on terminal close
defnonblock on
# Set message timeout
msgwait 0
# Clean up dead sessions
defzombie "^["
Server-Side SSH Configuration
Configure your SSH server to handle disconnections better. Add to /etc/ssh/sshd_config
:
# Reduce the time SSH waits before cleaning up dead connections
ClientAliveInterval 30
ClientAliveCountMax 3
# This means SSH will send a keepalive after 30 seconds of inactivity
# and disconnect after 3 failed keepalives (90 seconds total)
Client-Side SSH Configuration
Add to your ~/.ssh/config
:
Host *
ServerAliveInterval 60
ServerAliveCountMax 2
TCPKeepAlive yes
The Ultimate Automatic Setup
Create this wrapper function in your server’s ~/.bashrc
:
# Automatically use screen for all SSH sessions
if [[ -n "$SSH_CONNECTION" ]] && [[ "$TERM" != "screen"* ]] && command -v screen >/dev/null; then
# Get session name from current directory or hostname
SESSION_NAME="${SCREEN_SESSION_NAME:-$(basename "$PWD")}"
# Check if we're already in a screen session
if [ -z "$STY" ]; then
# Try to attach to existing session or create new one
screen -DR "$SESSION_NAME"
# Exit the SSH session when screen exits
exit
fi
fi
# Function to force-attach to any session
attach() {
local session="${1:-$(basename "$PWD")}"
screen -DR "$session"
}
With this setup:
- Every SSH login automatically creates/attaches to a screen session
- Closing your laptop lid doesn’t require any action
- Sessions are named after your current directory
- Dead connections are cleaned up automatically
Handling “Already Attached” Issues
Sometimes when you disconnect abruptly (like closing the laptop), the session might still show as attached. Here’s a foolproof reconnection function:
# Add to your server's ~/.bashrc
reconnect() {
local session="${1:-$(basename "$PWD")}"
# First, try to detach any existing connections
screen -d "$session" 2>/dev/null
# Then attach
screen -r "$session" 2>/dev/null || screen -DR "$session"
}
# Alias for quick access
alias re='reconnect'
Handling Multiple Locations
For those who work from multiple locations, consider this naming convention:
# Location-based sessions
screen -S "work-$(basename "$PWD")"
screen -S "home-$(basename "$PWD")"
screen -S "coffee-shop-$(basename "$PWD")"
Advanced Screen Features
Window Management
Within a screen session, you can create multiple windows:
# Inside a screen session:
# Create new window: Ctrl+A, then C
# Switch between windows: Ctrl+A, then N (next) or P (previous)
# List windows: Ctrl+A, then W
# Name current window: Ctrl+A, then A
# Switch to window by number: Ctrl+A, then [0-9]
Split Screen
Screen supports splitting your terminal:
# Horizontal split: Ctrl+A, then S
# Vertical split: Ctrl+A, then |
# Navigate splits: Ctrl+A, then Tab
# Close current split: Ctrl+A, then X
# Close all splits except current: Ctrl+A, then Q
Scrollback and Copy Mode
# Enter copy/scrollback mode: Ctrl+A, then [
# Navigate with arrow keys or vim keys (hjkl)
# Start selection: Space
# Copy selection: Space again
# Paste: Ctrl+A, then ]
Session Sharing
Perfect for pair programming or getting help:
# Start a session with multiuser mode
screen -S shared-session
# Inside screen, enable multiuser
# Press Ctrl+A, then :
# Type: multiuser on
# Type: acladd other_username
# Other user can now attach
screen -x username/shared-session
Screen with Development Tools
Claude Code Integration
When using Claude Code in screen sessions:
# Create a dedicated Claude Code session
screen -S claude-$(basename "$PWD")
# Inside the session
claude-code .
# If Claude Code needs to create new windows/panes
# Use Ctrl+A, then C for new window
Long-Running Processes
Perfect for processes that need to run continuously:
# Development servers
screen -S dev-server -dm npm run dev
# Database migrations
screen -S migration -dm python manage.py migrate
# Log monitoring
screen -S logs -dm tail -f /var/log/application.log
# Check on them later
screen -r logs
Git Operations
For long-running git operations:
# Large repository clones
screen -S git-clone
git clone https://github.com/large/repository.git
# Can detach and check progress later
screen -r git-clone
Automating Your Screen Workflow
SSH Config Integration
Add to ~/.ssh/config
:
Host dev-auto
HostName dev-server.com
User yourusername
RequestTTY force
RemoteCommand screen -DR main
Host dev-project
HostName dev-server.com
User yourusername
RequestTTY force
RemoteCommand cd ~/projects/myproject && screen -DR myproject
Now ssh dev-auto
automatically attaches to your main session.
Startup Scripts
Create ~/.screenrc
for customization:
# Enable 256 colors
term screen-256color
# Increase scrollback buffer
defscrollback 10000
# Display a caption line at the bottom
caption always "%{= kw}%-w%{= BW}%n %t%{-}%+w %-= %{= kw}%H %{= kw}%Y-%m-%d %c"
# Start with multiple named windows
screen -t "Editor" 0
screen -t "Server" 1
screen -t "Logs" 2
# Default to bash
shell -bash
# Skip startup message
startup_message off
# Automatic detach on disconnect
autodetach on
Project-Specific Screen Configurations
Create .screenrc.project
files:
# .screenrc.webdev
source ~/.screenrc
screen -t "Frontend" 0 bash -c 'cd frontend && bash'
screen -t "Backend" 1 bash -c 'cd backend && bash'
screen -t "Database" 2 bash -c 'cd database && bash'
screen -t "Logs" 3 bash -c 'tail -f logs/*.log'
# Start it with
screen -c .screenrc.webdev -S webproject
Troubleshooting Common Issues
“Cannot open your terminal” Error
# Fix with
script /dev/null
screen -r session-name
Dead Sessions
# List all sessions including dead ones
screen -ls
# Clean up dead sessions
screen -wipe
# Force detach and reattach
screen -D -r session-name
Permission Issues
# If you can't attach to your own session
# Check the socket directory
ls -la /var/run/screen/S-$USER/
# Fix permissions
chmod 700 /var/run/screen/S-$USER
Session Exists but Can’t Attach
# Force detach all clients and attach
screen -D -RR session-name
# If still issues, check who's attached
screen -ls
# Kill the session if necessary
screen -S session-name -X quit
Best Practices and Tips
1. Naming Conventions
Develop a consistent naming scheme:
# By project
screen -S proj-website
screen -S proj-api
screen -S proj-mobile
# By task type
screen -S dev-frontend
screen -S ops-monitoring
screen -S debug-issue123
# By date for temporary sessions
screen -S temp-$(date +%Y%m%d-%H%M)
2. Session Documentation
Keep track of what’s running where:
# Create a session info function
function screen-info() {
echo "=== Screen Sessions ==="
screen -ls
echo ""
echo "=== Session Contents ==="
for session in $(screen -ls | grep -o '[0-9]*\.[^ ]*' | cut -d. -f2); do
echo "Session: $session"
# You can add notes about what each session contains
done
}
3. Emergency Escape
If screen becomes unresponsive:
# The nuclear option - kill all screens
killall screen
# Or more targeted
screen -ls | grep Dead | awk '{print $1}' | xargs -I {} screen -S {} -X quit
4. Resource Management
# Limit memory usage in .screenrc
# Limit scrollback to prevent memory bloat
defscrollback 5000
# Monitor resource usage
# While in screen: Ctrl+A, then i (shows info)
5. Security Considerations
# Use screen with SSH keys only
# Disable password logins in sshd_config
# Lock your screen session
# Inside screen: Ctrl+A, then x
# Sets a password for the session
# Clear scrollback buffer before detaching sensitive sessions
# Ctrl+A, then :
# Type: scrollback 0
Conclusion
GNU Screen transforms the way you work with remote systems. No more lost sessions, no more restarting everything after a connection drop, and no more frustration when switching between work locations. Whether you’re using Claude Code for AI-assisted development, managing servers, or running long data analysis jobs, Screen ensures your work persists exactly as you left it.
The key to mastering Screen is to make it part of your daily workflow. Start with simple named sessions, then gradually incorporate more advanced features as they become relevant to your work. Before long, you’ll wonder how you ever managed without it.
Remember: Every SSH session without Screen is a session you might lose. Make Screen your default, and enjoy the peace of mind that comes with truly persistent remote work sessions.
Quick Reference Card
# Essential Commands
screen -S name # New named session
screen -ls # List sessions
screen -r name # Reattach to session
Ctrl+A, d # Detach
Ctrl+A, c # New window
Ctrl+A, n/p # Next/Previous window
Ctrl+A, " # Window list
Ctrl+A, k # Kill window
Ctrl+A, ? # Help
# Remember: Start every SSH session with Screen!
Leave a Reply