Saltar a contenido

Screen

Pantalla Cheatsheet

Overview

GNU Screen es un multiplexor terminal que permite ejecutar múltiples sesiones de terminal dentro de una sola ventana terminal. Permite la persistencia de la sesión, el desapego y el reagrupamiento, por lo que es ideal para el trabajo a distancia y los procesos de larga duración.

Instalación

Package Managers

# Ubuntu/Debian
sudo apt install screen

# macOS
brew install screen

# CentOS/RHEL
sudo yum install screen

# Arch Linux
sudo pacman -S screen

# From source
wget https://ftp.gnu.org/gnu/screen/screen-4.9.0.tar.gz
tar -xzf screen-4.9.0.tar.gz
cd screen-4.9.0 && ./configure && make && sudo make install

Uso básico

Start Screen

# Start new screen session
screen

# Start named session
screen -S sessionname

# Start session with command
screen -S mysession htop

# Start detached session
screen -d -m -S mysession

# Start session with specific shell
screen -S mysession bash

Session Management

# List sessions
screen -ls
screen -list

# Attach to session
screen -r sessionname
screen -r 12345  # Using session ID

# Attach to session (force if attached elsewhere)
screen -d -r sessionname

# Detach from session
# Inside screen: Ctrl+a d

# Kill session
screen -S sessionname -X quit

# Kill all sessions
pkill screen

Cadenas clave (Prefijo predeterminado: Ctrl+a)

Comandos de sesión

Ctrl+a d    # Detach from session
Ctrl+a D D  # Detach and logout
Ctrl+a \    # Kill all windows and terminate
Ctrl+a :    # Enter command mode

Window Commands

Ctrl+a c    # Create new window
Ctrl+a n    # Next window
Ctrl+a p    # Previous window
Ctrl+a 0-9  # Switch to window by number
Ctrl+a "    # List windows
Ctrl+a w    # Show window list
Ctrl+a k    # Kill current window
Ctrl+a A    # Rename current window
Ctrl+a '    # Prompt for window number to switch to

Window Navigation

Ctrl+a Ctrl+a  # Switch to last window
Ctrl+a l       # Refresh screen
Ctrl+a L       # Toggle login state
Ctrl+a M       # Monitor window for activity
Ctrl+a _       # Monitor window for silence

Split Screen (Regiones)

Ctrl+a S    # Split horizontally
Ctrl+a|# Split vertically (if supported)
Ctrl+a Tab  # Switch between regions
Ctrl+a Q    # Close all regions except current
Ctrl+a X    # Close current region

Copy Mode

Ctrl+a [    # Enter copy mode
Ctrl+a ]    # Paste buffer
Ctrl+a >    # Write buffer to file
Ctrl+a <    # Read buffer from file

Copy Mode Navigation

Enter Copy Mode

Ctrl+a [    # Enter copy mode
Ctrl+a Esc  # Enter copy mode (alternative)

Movimiento en modo de copia

h, j, k, l  # Move cursor (vi-style)
Arrow keys  # Move cursor
w           # Next word
b           # Previous word
0           # Beginning of line
$           # End of line
g           # Go to beginning of buffer
G           # Go to end of buffer
Ctrl+f      # Page down
Ctrl+b      # Page up
/           # Search forward
?           # Search backward
n           # Next search result
N           # Previous search result

Selección y copia

Space       # Start/end selection
Enter       # Copy selection and exit copy mode
Esc         # Exit copy mode

Configuración

Archivo de configuración (~/.screenrc)

# Basic settings
startup_message off
defscrollback 10000
hardstatus alwayslastline
hardstatus string '%\\\\{= kG\\\\}[ %\\\\{G\\\\}%H %\\\\{g\\\\}][%= %\\\\{=kw\\\\}%?%-Lw%?%\\\\{r\\\\}(%\\\\{W\\\\}%n*%f%t%?(%u)%?%\\\\{r\\\\})%\\\\{w\\\\}%?%+Lw%?%?%= %\\\\{g\\\\}][%\\\\{B\\\\}%Y-%m-%d %\\\\{W\\\\}%c %\\\\{g\\\\}]'

# Set default shell
shell -$SHELL

# Enable 256 colors
term screen-256color

# Mouse support (if available)
mousetrack on

# Automatically detach on hangup
autodetach on

# Change escape key
escape ^Aa  # Default is Ctrl+a

# Window numbering
bind c screen 1
bind ^c screen 1
bind 0 select 10
screen 1

# Split screen bindings
bind|split -v
bind - split
bind + resize +5
bind = resize =
bind _ resize -5

# Window navigation
bind j focus down
bind k focus up
bind h focus left
bind l focus right

# Reload config
bind r source ~/.screenrc

# Logging
bind L log

# Monitor activity
bind m monitor
bind M monitor

Configuración avanzada

# Status line customization
hardstatus on
hardstatus alwayslastline
hardstatus string "%\\\\{.bW\\\\}%-w%\\\\{.rW\\\\}%n %t%\\\\{-\\\\}%+w %=%\\\\{..G\\\\} %H %\\\\{..Y\\\\} %m/%d %C%a "

# Window titles
shelltitle "$|bash"

# Startup windows
screen -t "editor" 1 vim
screen -t "server" 2
screen -t "logs" 3 tail -f /var/log/messages

# Key bindings for common tasks
bind ^k kill
bind k kill
bind ^\ quit
bind \\ quit
bind ^h hardcopy
bind h hardcopy

# Scrollback buffer
defscrollback 10000

# Visual bell
vbell on
vbell_msg "   Wuff  ----  Wuff!!  "

# Activity monitoring
activity "Activity in %t(%n)"

# Silence monitoring
silence on
silencewait 15

# Automatic window naming
shelltitle '$|bash'

# Password protection
password ODSJQf.4IJN7E    # Encrypted password

# Multiuser mode
multiuser on
acladd user1,user2

Características avanzadas

Múltiples usuarios

# Enable multiuser mode
screen -S shared
# In screen: Ctrl+a :multiuser on
# In screen: Ctrl+a :acladd username

# Other user connects
screen -x username/shared

Session Sharing

# Start shared session
screen -S shared

# Allow others to attach
# In screen: Ctrl+a :multiuser on
# In screen: Ctrl+a :acladd otheruser

# Other user attaches
screen -x shared

Logging

# Enable logging for window
# In screen: Ctrl+a H

# Log to specific file
# In .screenrc:
logfile /tmp/screen-%t.log

# Automatic logging
deflog on

Monitoring

# Monitor window for activity
Ctrl+a M

# Monitor for silence
Ctrl+a _

# Set silence timeout (seconds)
# In .screenrc:
silencewait 30

Command Line Options

Session Management

# Create detached session
screen -d -m -S mysession

# Create session and run command
screen -d -m -S mysession bash -c 'cd /var/log && tail -f messages'

# Send command to session
screen -S mysession -X stuff 'ls -la\n'

# Send command to specific window
screen -S mysession -p 0 -X stuff 'htop\n'

# Capture window content
screen -S mysession -p 0 -X hardcopy /tmp/screen.dump

Window Management

# Create window with title
screen -S mysession -X screen -t "editor" vim

# Kill specific window
screen -S mysession -p 1 -X kill

# List windows
screen -S mysession -Q windows

Scripting

Automation Scripts

#!/bin/bash
# dev-setup.sh

SESSION="development"

# Check if session exists
if ! screen -list|grep -q "$SESSION"; then
    # Create new session
    screen -d -m -S "$SESSION"

    # Setup windows
    screen -S "$SESSION" -X screen -t "editor" 1 vim
    screen -S "$SESSION" -X screen -t "server" 2
    screen -S "$SESSION" -X screen -t "logs" 3 tail -f /var/log/messages

    # Send commands to windows
    screen -S "$SESSION" -p 2 -X stuff 'cd ~/project && npm start\n'

    # Select first window
    screen -S "$SESSION" -X select 1
fi

# Attach to session
screen -r "$SESSION"

Batch Operations

# Kill all sessions
screen -ls|grep Detached|cut -d. -f1|awk '\\\\{print $1\\\\}'|xargs kill

# Send command to all windows
for i in \\\\{0..9\\\\}; do
    screen -S mysession -p $i -X stuff 'echo "Hello from window $i"\n'
done

# Create multiple sessions
for name in web api db; do
    screen -d -m -S "$name"
done

Integration

With SSH

# Auto-start screen on SSH login
# Add to ~/.bashrc on remote server
if [ -z "$STY" ] && [ -n "$SSH_CONNECTION" ]; then
    screen -RR ssh_session
fi

# Or use a function
ssh_screen() \\\\{
    ssh -t "$1" 'screen -RR'
\\\\}

With System Services

# Run service in screen
screen -d -m -S myservice /path/to/service

# Systemd service file
[Unit]
Description=My Service in Screen
After=network.target

[Service]
Type=forking
User=myuser
ExecStart=/usr/bin/screen -d -m -S myservice /path/to/service
ExecStop=/usr/bin/screen -S myservice -X quit

[Install]
WantedBy=multi-user.target

Comparación con tmux

Screen vs tmux

Screen:
+ Older, more stable
+ Simpler configuration
+ Better for basic use cases
+ Lower resource usage
- Less active development
- Fewer features
- Limited pane support

tmux:
+ More active development
+ Better pane management
+ More features
+ Better scripting support
- Steeper learning curve
- More complex configuration

Consejos y trucos

Consejos de productividad

# Quick session switching
alias s='screen -ls'
alias sr='screen -r'
alias sn='screen -S'

# Function to create or attach
sc() \\\\{
    if [ $# -eq 0 ]; then
        screen -ls
    else
        screen -r "$1"||screen -S "$1"
    fi
\\\\}

# Nested screen sessions
# Change escape key for inner session
# In .screenrc: escape ^Bb

Aliases útiles

# Add to ~/.bashrc
alias sl='screen -ls'
alias sr='screen -r'
alias ss='screen -S'
alias sk='screen -X -S'

# Function for easy session management
screen_session() \\\\{
    case "$1" in
        ls|list)
            screen -ls
            ;;
        new)
            screen -S "$2"
            ;;
        attach)
            screen -r "$2"
            ;;
        kill)
            screen -S "$2" -X quit
            ;;
        *)
            echo "Usage: screen_session \\\\{ls|new|attach|kill\\\\} [session_name]"
            ;;
    esac
\\\\}

Troubleshooting

Common Issues

# Fix "Cannot open your terminal '/dev/pts/0'" error
script /dev/null

# Or use:
screen -x

# Dead session cleanup
screen -wipe

# Permission issues
chmod 755 /var/run/screen

# Check screen version
screen -v

# Debug mode
screen -d -m -L -S debug command

Recuperación

# Recover dead sessions
screen -D -R

# Force detach and reattach
screen -d sessionname
screen -r sessionname

# Clean up dead sessions
screen -wipe

Seguridad

Access Control

# Set password protection
# In .screenrc:
password your_encrypted_password

# Generate encrypted password
screen -X password

# Multiuser access control
multiuser on
acladd username
aclchg username +rwx "#"

Buenas prácticas

# Use named sessions
screen -S descriptive_name

# Regular cleanup
screen -wipe

# Monitor session activity
# In .screenrc:
activity "Activity in %t(%n)"

# Limit scrollback buffer
defscrollback 1000

Resources

Documentación oficial: [gnu.org/software/screen](URL_33_ Manual - Info**: - ¿Por qué?