---
title: "Screen"
description: "GNU Screen is a terminal multiplexer that allows you to manage multiple terminal sessions, windows, and panes within a single screen. Essential commands for session, window management and splitting."
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/cheatsheets/screen
---

# Screen

## Getting Started

GNU Screen is a powerful terminal multiplexer that gives you:

- **Sessions**: Full terminal environments that persist even if you disconnect
- **Windows**: Multiple terminals (tabs) within a single session
- **Splits**: Horizontal and vertical screen divisions for side-by-side work
- **Copy/Paste**: Built-in text selection and clipboard management
- **Automation**: Scripts to auto-setup complex terminal layouts

Start your first screen session:

```bash
screen -S development
```

Then detach with `Ctrl+A d` and reattach from anywhere:

```bash
screen -r development
```

## Key Concepts

**Sessions**: Independent workspaces that continue running even if you disconnect. Great for long-running server processes and preserving work state.

**Windows**: Tabs within a session. Each window is a full terminal shell with independent directory and command history.

**Splits**: Horizontal regions within a window. Allows side-by-side terminals without creating new windows (though for complex panes, tmux may be better).

**Copy Mode**: Special mode for selecting and copying text from the scrollback buffer for pasting later.

## Essential Keybindings

All keybindings use the prefix key `Ctrl+A` (abbreviated as `C-a`):

### Session Management

- `C-a d` - Detach from session (background)
- `C-a D D` - Detach and logout
- `C-a q` - Exit screen

### Windows

- `C-a c` - Create new window
- `C-a n` / `C-a p` - Next/previous window
- `C-a [0-9]` - Jump to window number
- `C-a w` - List all windows
- `C-a k` - Kill current window
- `C-a A` - Rename window

### Splits and Regions

- `C-a S` - Split horizontally (regions)
- `C-a |` - Split vertically (newer versions)
- `C-a Tab` - Switch to next region
- `C-a X` - Remove current region
- `C-a Q` - Remove all regions

### Copy and Paste

- `C-a [` - Enter copy/scroll mode
- `Space` - Start selection (in copy mode)
- `Enter` - Copy selection (in copy mode)
- `C-a ]` - Paste copied text
- `C-a =` - Show paste buffers

## Common Screen Setup

Install and create your configuration file `~/.screenrc`:

```bash
# ~/.screenrc - Essential configuration
# Increase scrollback history
defscrollback 10000

# Enable 256-color terminal
term screen-256color

# Don't show startup message
startup_message off

# Enable visual bell for notifications
vbell on

# Automatically detach on connection loss
autodetach on

# Useful custom bindings
bind h select -1
bind l select +1
bind - split -h
bind _ split -v
```

Load the config:

```bash
screen -c ~/.screenrc
```

## Building a Development Session

Create a complete development environment automatically:

```bash
#!/bin/bash
# dev-session.sh - Create development environment

SESSION="dev"
screen -S "$SESSION" -d -m

# Create editor window
screen -S "$SESSION" -X new-window -t "editor"
screen -S "$SESSION" -p "editor" -X send-keys "cd ~/myproject && vim" Enter

# Create server window
screen -S "$SESSION" -X new-window -t "server"
screen -S "$SESSION" -p "server" -X send-keys "cd ~/myproject && npm start" Enter

# Create test window
screen -S "$SESSION" -X new-window -t "test"
screen -S "$SESSION" -p "test" -X send-keys "cd ~/myproject && npm test" Enter

# Attach and start
screen -r "$SESSION"
```

Run it anytime: `bash dev-session.sh`

## Tips for Productivity

1. **Use Named Sessions**: `screen -S projectname` is easier to remember than numbered sessions
2. **Name Your Windows**: Use `C-a A` to name windows (editor, server, monitor)
3. **Detach Don't Exit**: Always use `C-a d` to detach, not `exit`, so session persists
4. **Create Session Templates**: Save setup scripts for recurring project types
5. **Organize by Project**: One session per project with windows for different tasks
6. **Use Splits for Monitoring**: Split regions work well for watching logs while you work
7. **Enable Scrollback**: Set `defscrollback 10000` in ~/.screenrc for adequate history
8. **Combine with SSH**: Screen is invaluable over SSH for long-running remote tasks

## Quick Reference: Session Lifecycle

```bash
# Create session
screen -S mywork

# Inside screen - work normally, then detach
Ctrl+A d

# Check sessions
screen -ls

# Reattach to session
screen -r mywork

# Kill session when done
screen -S mywork -X quit
```

## Screen vs Tmux

**Screen is better for:**

- Simplicity - smaller learning curve
- Systems where tmux isn't available
- Simple split layouts (left/right only)
- Older servers that predate tmux

**Tmux is better for:**

- Complex pane management
- Modern development workflows
- Extensive plugin ecosystem
- Latest terminal features

## Resources

- Official GNU Screen Manual: https://www.gnu.org/software/screen/
- Linux Manual Page: https://linux.die.net/man/1/screen
- Practical Screen Tutorial: https://www.rackaid.com/blog/linux-screen-tutorial-and-how-to/

## Getting Started

Start using screen and learn basic concepts

### Installation and Basics

Install screen and understand what it does

**Keywords:** install, setup, start, launch, screen

#### Install Screen on Linux

```bash
# On Debian/Ubuntu
sudo apt-get install screen

# On RedHat/CentOS/Fedora
sudo yum install screen

# On macOS with Homebrew
brew install screen

# Verify installation
screen --version
```

_exec_
```bash
screen --version
```

_output_
```bash
Screen version 4.09.00 (GNU) 23-Oct-22
```

Installs GNU Screen terminal multiplexer and verifies the installation.

- Most Linux distributions include screen by default
- Screen is lightweight and available on almost all Unix-like systems
- No special permissions required to run screen

#### Start Screen without a session name

```bash
# Start a basic screen session
screen

# Start screen with UTF-8 support
screen -U

# Start and list existing sessions
screen -ls
```

_exec_
```bash
screen -ls
```

_output_
```bash
There is a screen on:
	12345.pts-0.myhost	(Attached)
```

Launches Screen and shows running sessions.

- Creates a numbered session (starts from 0)
- -U flag enables UTF-8 character support
- Attached status indicates active session

**Best practices:**

- Always name sessions with descriptive names for better organization
- Use screen -ls regularly to check running sessions
- Set SCREENDIR for custom session storage if needed

**Common errors:**

- **screen is not installed**: Install with apt-get, yum, or brew depending on your OS

### Understanding Screen Concepts

Learn the hierarchical structure of screen

**Keywords:** concepts, structure, hierarchy, sessions, windows

#### Understanding screen session and window hierarchy

```text
Session (development)
├── Window 0 (shell)
├── Window 1 (editor)
├── Window 2 (build)
└── Window 3 (testing)
```

_exec_
```bash
screen -ls development
```

_output_
```bash
There are screens on:
	12345.development	(Attached)
```

Screen organizes your work into sessions containing multiple numbered windows.

- One session can contain many windows (like terminal tabs)
- Unlike tmux, screen does not have panes (but can split horizontally)
- Each window maintains its own shell environment and history

#### Check current screen setup

```bash
# Inside screen session - show info
Ctrl+A i

# List all windows in current session
Ctrl+A w

# Show current window number
Ctrl+A N
```

_exec_
```bash
screen -version && echo 'Screen ready'
```

_output_
```bash
Screen version 4.09.00 && Screen ready
```

View information about your current screen session and windows.

- Ctrl+A is the default command prefix in screen
- Window list shows all open windows with their numbers and names
- Most operations inside screen use Ctrl+A prefix

**Best practices:**

- Understand the difference between sessions and windows
- Use meaningful window names for quick navigation
- Keep related tasks in the same session

**Common errors:**

- **no session to which to attach**: Create a new session first with screen -S sessionname

### Creating Your First Session

Create and manage your first screen session

**Keywords:** new, create, session, start, named

#### Create a named screen session

```bash
# Create a new named session
screen -S mywork

# Create session and execute command
screen -S development -d -m "bash -c 'echo Starting development'"

# Create session in detached mode
screen -S build -d
```

_exec_
```bash
screen -S test -d
```

_output_
```bash
[screen created]
```

Creates a named screen session (with -S) that's easier to remember and reattach to.

- -S flag specifies the session name
- -d flag starts session detached (in background)
- -m flag allows starting with a command
- Named sessions are much better than numbered ones

#### Attach to a session

```bash
# List all available sessions
screen -ls

# Attach to a specific session
screen -r mywork

# Attach if already attached, multi-display
screen -x mywork

# Force reattach if needed
screen -r -d mywork
```

_exec_
```bash
screen -ls
```

_output_
```bash
There are screens on:
	12345.mywork		(Detached)
	12346.development	(Attached)
```

List all sessions and attach to the one you want to work with.

- -r attaches to a detached session
- -x allows multiple users to view same session
- -d flag forces detach of other connections

**Best practices:**

- Use descriptive names like 'work', 'dev', 'server', 'build'
- Detach sessions instead of killing them to preserve work
- Reattach to preserved sessions later

**Common errors:**

- **screen already exists**: Use screen -r -d to force reattach

## Session Management

Work with multiple screen sessions

### Create and Attach Sessions

Create new sessions and attach to existing ones

**Keywords:** create, new, attach, start, session

#### Create multiple independent sessions

```bash
# Create session for development
screen -S dev -d

# Create session for servers
screen -S servers -d

# Create session for testing
screen -S test -d

# List all created sessions
screen -ls
```

_exec_
```bash
screen -S workspace -d && screen -ls
```

_output_
```bash
There is a screen on:
	99999.workspace	(Detached)
```

Create multiple independent screen sessions for different projects or tasks.

- Each session is completely independent
- Sessions continue running even if you disconnect
- Great for long-running processes and server management

#### Attach and detach from sessions

```bash
# Attach to an existing session
screen -r dev

# Inside screen, detach with:
# Ctrl+A d (press Ctrl+A, release, then press D)

# Switch between windows in a session
# Ctrl+A [0-9] to jump to window number
# Ctrl+A n for next window
# Ctrl+A p for previous window
```

_exec_
```bash
screen -r
```

_output_
```bash
[attached to session]
```

Attach to your most recent session and navigate between windows.

- Detaching preserves your session - everything keeps running
- Ctrl+A is the command prefix for all screen operations
- You can reattach to any detached session later

**Best practices:**

- Detach from sessions instead of exiting shell to preserve work
- Use Ctrl+A d before closing terminal window
- Keep session names consistent across your workflow

**Common errors:**

- **cannot open /var/run/screen/permission denied**: Check screen permissions or use different screendir

### List and Monitor Sessions

View and manage all running sessions

**Keywords:** list, ls, monitor, check, status

#### List all screen sessions with details

```bash
# List all active sessions
screen -ls

# Get more detailed session info
screen -ls | grep -E '^\s+[0-9]'

# Check a specific session
screen -ls mywork

# List with additional stats
ps aux | grep SCREEN
```

_exec_
```bash
screen -ls
```

_output_
```bash
There are screens on:
	12345.dev		(Attached)
	12346.servers		(Detached)
	12347.testing		(Detached)
3 Sockets in /run/screen/S-user.
```

View all running screen sessions and their attachment status.

- Attached means session is currently being viewed in a terminal
- Detached sessions continue running in the background
- Shows number of sockets (connection points) to session

#### Monitor and manage session processes

```bash
# Inside screen - show window list info
Ctrl+A w

# Show last 30 lines activity
Ctrl+A g

# Display current screen size
echo $LINES x $COLUMNS

# Kill a session from outside
screen -S mywork -X quit

# Send command to detached session
screen -S mywork -X send-keys "ls -la" Enter
```

_exec_
```bash
screen -S worker -X send-keys "echo hello" Enter
```

_output_
```bash
hello
```

Monitor active processes and send commands to sessions remotely.

- -X allows sending commands to sessions without attaching
- send-keys can execute commands in detached sessions
- Very useful for automation and monitoring

**Best practices:**

- Regularly check session status with screen -ls
- Use meaningful session names for easy identification
- Monitor long-running processes regularly

**Common errors:**

- **cannot find session**: Verify session name with screen -ls

### Kill and Destroy Sessions

Terminate sessions and clean up resources

**Keywords:** kill, quit, terminate, destroy, end

#### Properly terminate screen sessions

```bash
# Kill session from outside
screen -S mywork -X quit

# Inside screen, exit shell to kill session
exit

# Inside screen, use Ctrl+A k to kill current window
Ctrl+A k

# Force kill a stuck session
kill -9 $(pgrep -f 'SCREEN.*mywork')

# Clean up all dead sessions
screen -wipe
```

_exec_
```bash
screen -S temp -d && screen -S temp -X quit && screen -ls
```

_output_
```bash
No Sockets found.
```

Terminate screen sessions cleanly or forcefully when needed.

- exit command closes shell and kills session gracefully
- Ctrl+A k kills only current window, not entire session
- -X quit is cleanest remote termination method
- kill -9 should be last resort for stuck sessions

#### Handle zombie and dead sessions

```bash
# List sessions including dead ones
screen -ls

# Remove dead sessions
screen -wipe

# Clear out orphaned screen processes
killall -v screen

# Verify cleanup
screen -ls
```

_exec_
```bash
screen -wipe
```

_output_
```bash
[dead sessions removed]
```

Clean up dead or orphaned screen sessions.

- Dead sessions occur when session crashes or terminal closes abruptly
- screen -wipe removes dead sessions automatically
- Only use killall screen if absolutely necessary

**Best practices:**

- Always detach before closing terminal to preserve session
- Use exit command gracefully to close sessions
- Run screen -wipe periodically to clean dead sessions

**Common errors:**

- **cannot create socket**: Run screen -wipe to clean dead sessions

## Window Management

Create and navigate multiple windows within a session

### Create and Switch Windows

Create new windows and navigate between them

**Keywords:** create, new, window, switch, navigate, jump

#### Create new windows in a session

```bash
# Inside screen - create new window
Ctrl+A c

# Create window with a specific shell command
Ctrl+A :screen -t "editor" vim

# Create window and name it
Ctrl+A :title editor

# Create numbered window sequence
for i in {1..5}; do
  screen -S dev -X new-window -t dev:$i
done
```

_exec_
```bash
echo "Use Ctrl+A c inside screen to create windows"
```

_output_
```bash
Use Ctrl+A c inside screen to create windows
```

Create multiple windows within a screen session for different tasks.

- Each window is independent with its own shell
- Window numbering starts at 0 by default
- Windows can have friendly names for easy identification
- -t flag specifies window title during creation

#### Switch between windows efficiently

```bash
# Jump to window by number (0-9)
Ctrl+A 0  # Jump to window 0
Ctrl+A 1  # Jump to window 1
Ctrl+A 2  # Jump to window 2

# Move to next/previous window
Ctrl+A n  # Next window
Ctrl+A p  # Previous window

# Switch to last active window
Ctrl+A Ctrl+A

# List all windows
Ctrl+A w
```

_exec_
```bash
echo "Inside screen session use Ctrl+A w to see all windows"
```

_output_
```bash
Inside screen session use Ctrl+A w to see all windows
```

Navigate quickly between windows using keyboard shortcuts.

- Ctrl+A w shows visual list of all windows
- Ctrl+A Ctrl+A toggles between last two windows
- Direct number access (Ctrl+A 0-9) is fastest for frequent windows

**Best practices:**

- Create windows for different logical tasks (editor, build, test, monitor)
- [object Object]
- Keep frequently used windows numbered 0-3 for quick access

**Common errors:**

- **window already exists**: Use screen -ls to see existing windows

### Manage and Close Windows

Rename, close, and organize windows

**Keywords:** manage, rename, close, kill, arrange

#### Rename and manage windows

```bash
# Rename current window (inside screen)
Ctrl+A A

# Change window title in command mode
Ctrl+A :title newname

# Rename from shell (outside screen)
screen -S mywork -p number -X title newname

# Move window to different position
Ctrl+A :number position
```

_exec_
```bash
echo "Press Ctrl+A A inside screen to rename current window"
```

_output_
```bash
Press Ctrl+A A inside screen to rename current window
```

Rename windows to organize and identify them clearly.

- Ctrl+A A opens rename prompt in current window
- window names help identify purpose at a glance
- Can set window titles programmatically

#### Close windows and manage cleanup

```bash
# Kill current window (inside screen)
Ctrl+A k

# Close window with confirmation
Ctrl+A K

# Exit shell in window (closes window)
exit

# Remove specific window from shell
screen -S mywork -p 2 -X kill

# List and close all windows except current
Ctrl+A :killall
```

_exec_
```bash
echo "Use Ctrl+A k to kill current window"
```

_output_
```bash
Use Ctrl+A k to kill current window
```

Close and remove windows when no longer needed.

- Ctrl+A k kills window immediately
- Ctrl+A K asks for confirmation before killing
- exit command also closes the window gracefully

**Best practices:**

- Use clear naming convention for windows
- Don't have too many windows - keep to 5-10 max
- Close unused windows to reduce clutter

**Common errors:**

- **cannot kill only window**: Session ends when you kill the last window

### Window Navigation Tips

Advanced techniques for efficient window navigation

**Keywords:** navigate, jump, switch, jump, efficient

#### Speed up window switching

```bash
# Quick jump to numbered windows
Ctrl+A 0  # Fastest for frequently used windows
Ctrl+A 1
Ctrl+A 9

# Cycle through windows
Ctrl+A n      # Next
Ctrl+A p      # Previous
Ctrl+A Ctrl+A # Last active

# List windows with full details
Ctrl+A w
```

_exec_
```bash
echo "For windows 0-9, use Ctrl+A + number"
```

_output_
```bash
For windows 0-9, use Ctrl+A + number
```

Master quick navigation between windows.

- Direct number access is fastest for frequent switches
- Keep important windows at positions 0-3
- Ctrl+A Ctrl+A is useful for two-window workflows

#### Configure custom window switching

```bash
# In ~/.screenrc - create custom bindings
# Example - use Alt+number for windows
bind 'M-1' select 1
bind 'M-2' select 2
bind 'M-3' select 3

# Or use simpler keybindings
bind 'h' select -1
bind 'l' select +1
```

_exec_
```bash
echo "Configure .screenrc for custom keybindings"
```

_output_
```bash
Configure .screenrc for custom keybindings
```

Customize keybindings for faster window navigation in your workflow.

- Custom keybindings require ~/.screenrc configuration
- M- prefix refers to Meta/Alt key
- Changes take effect after screen restart

**Best practices:**

- Map shortcuts to your muscle memory
- Use vim-like h/l for left/right navigation
- Test shortcuts before integrating into workflow

**Common errors:**

- **keybinding not working**: Check ~/.screenrc syntax and reload screen

## Splitting Screens

Split windows horizontally and vertically

### Horizontal and Vertical Splits

Split windows in different directions

**Keywords:** split, horizontal, vertical, region, pane

#### Create screen splits

```bash
# Split horizontally (top/bottom)
Ctrl+A S

# Split vertically (left/right)
Ctrl+A |

# Create complex layouts
Ctrl+A S      # First split - creates top region
Ctrl+A Tab    # Move to new region
Ctrl+A c      # Create window in top region
Ctrl+A S      # Split again

# Remove current split
Ctrl+A X
```

_exec_
```bash
echo "Use Ctrl+A S for horizontal, Ctrl+A | for vertical"
```

_output_
```bash
Use Ctrl+A S for horizontal, Ctrl+A | for vertical
```

Create horizontal and vertical splits in screen windows.

- Horizontal split creates top/bottom regions
- Vertical split creates left/right regions (in newer screens)
- Each split region can display different windows
- Vertical split may not work in older screen versions

#### Manage complex split layouts

```bash
# Split the window in half
Ctrl+A S

# Switch to bottom region
Ctrl+A Tab

# Create another window in bottom
Ctrl+A c

# Split bottom region vertically
Ctrl+A |

# Navigate to each region
Ctrl+A Tab  # Cycle through regions

# Remove current region
Ctrl+A X
```

_exec_
```bash
echo "Layouts: press Tab to cycle through split regions"
```

_output_
```bash
Layouts: press Tab to cycle through split regions
```

Create and manage multiple grouped split regions.

- Each split region is independent
- Tab cycles through different regions
- Better than tmux for simple side-by-side use cases

**Best practices:**

- Keep splits simple - 2-3 regions per window is ideal
- Use consistent window numbers across splits
- Remember layouts for common workflows

**Common errors:**

- **cannot split - too small**: Enlarge terminal window before splitting

### Navigate and Resize Splits

Move between and resize split regions

**Keywords:** navigate, resize, region, move, arrange

#### Navigate between split regions

```bash
# Move to next region
Ctrl+A Tab

# Move to top region
Ctrl+A Ctrl+I

# Display current region number
Ctrl+A Shift+I

# Switch to specific window in region
Ctrl+A 0-9  (in focused region)

# Rotate windows among regions
Ctrl+A C-T
```

_exec_
```bash
echo "Tab to navigate regions, then 0-9 to switch windows"
```

_output_
```bash
Tab to navigate regions, then 0-9 to switch windows
```

Navigate effectively between split regions.

- Tab is the primary method to move between regions
- Once in a region, number keys switch windows within it
- Visual feedback shows active region highlighting

#### Resize split regions

```bash
# Resize current region (make larger)
Ctrl+A +  (expand downward)
Ctrl+A -  (shrink)

# Auto-fit region to content
Ctrl+A F

# Equalize all region sizes
Ctrl+A E

# Fine-tune sizing
Ctrl+A :resize height
```

_exec_
```bash
echo "Use +/- keys to resize regions"
```

_output_
```bash
Use +/- keys to resize regions
```

Adjust split region sizes for optimal viewing.

- Plus/minus adjust region boundaries dynamically
- Resize affects the current focused region
- Works better in newer screen versions

**Best practices:**

- Arrange regions by importance - largest for main task
- Keep monitor task in smaller secondary region
- Reset layout when splits get confusing

**Common errors:**

- **region too small to navigate**: Resize larger with Ctrl+A + keys

### Remove and Reset Splits

Clear splits and reset layouts

**Keywords:** remove, reset, clear, quit, layout

#### Remove and reset split regions

```bash
# Remove current region
Ctrl+A X

# Remove all splits (show single region)
Ctrl+A Q

# Close all regions except current
Ctrl+A :only

# Reset layout to default
Ctrl+A :layout reset
```

_exec_
```bash
echo "Ctrl+A X to remove current region, Q to remove all"
```

_output_
```bash
Ctrl+A X to remove current region, Q to remove all
```

Clean up and remove screen splits when needed.

- Ctrl+A X removes only current region
- Ctrl+A Q removes all splits in window
- Windows are preserved even when splits removed

#### Save and restore layouts

```bash
# Save current layout (named layout)
Ctrl+A :layout save workname

# List saved layouts
Ctrl+A :layout list

# Restore saved layout
Ctrl+A :layout load workname

# Switch between layouts
Ctrl+A :layout select workname
```

_exec_
```bash
echo "Layout save/restore requires configuration"
```

_output_
```bash
Layout save/restore requires configuration
```

Save and restore frequently used split configurations.

- Layout save feature available in screen 4.01+
- Great for repeating complex split setups
- Saves time in daily workflows

**Best practices:**

- Save common layouts for quick recall
- [object Object]
- Test layout loading before relying on it

**Common errors:**

- **layout save not supported**: Update to screen 4.01 or newer

## Copy/Paste and Scrolling

Copy text and navigate scrollback buffer

### Copy Mode and Paste

Copy text from screen and paste it back

**Keywords:** copy, paste, text, clipboard, buffer

#### Enter copy mode and select text

```bash
# Enter copy/scroll mode
Ctrl+A [

# Move cursor in copy mode
- Use arrow keys to navigate
- Space to start selection
- Enter to copy selection
- Or use G to go to bottom

# Exit copy mode without copying
Escape

# Navigate in copy mode
h j k l  (vim style - if configured)
b      (back word)
f      (forward word)
```

_exec_
```bash
echo "Press Ctrl+A [ to enter copy mode"
```

_output_
```bash
Press Ctrl+A [ to enter copy mode
```

Enter copy mode to select and copy text from screen history.

- Copy mode shows scrollback buffer
- Can mark and copy multiple times without exiting
- Text stays in screen clipboard for pasting

#### Paste text and manage buffers

```bash
# Paste last copied text
Ctrl+A ]

# Show available paste buffers
Ctrl+A =

# Paste from specific buffer
Ctrl+A :paste buffer_name

# Copy directly from command
echo "text" | Ctrl+A [
```

_exec_
```bash
echo "Use Ctrl+A ] to paste copied text"
```

_output_
```bash
Use Ctrl+A ] to paste copied text
```

Paste previously copied text and manage multiple buffers.

- Ctrl+A ] pastes last copied selection
- Multiple buffers allow you to save different text snippets
- Clipboard is separate from system clipboard

**Best practices:**

- Use vim keybindings for faster selection in copy mode
- Name important buffers for easy recall
- Copy error messages for troubleshooting later

**Common errors:**

- **nothing in paste buffer**: Use Ctrl+A [ to copy text first

### Scrollback and Buffer Management

Navigate history and manage scrollback buffers

**Keywords:** scroll, history, buffer, backscroll, navigate

#### Navigate scrollback buffer

```bash
# Enter scrollback (scroll up in history)
Ctrl+A [

# Scroll up in history
Page Up  or  B

# Scroll down in history
Page Down  or  F

# Go to top of buffer
g      (go to top)
G      (go to bottom)

# Search in scrollback
/pattern   (forward search)
?pattern   (backward search)
n          (next match)
```

_exec_
```bash
echo "Ctrl+A [ enters scrollback mode"
```

_output_
```bash
Ctrl+A [ enters scrollback mode
```

Navigate and search through terminal history.

- Scrollback allows viewing past output
- Search helps find specific text in history
- Default scrollback is usually 100-1000 lines

#### Adjust scrollback buffer size

```bash
# In ~/.screenrc - increase history
defscrollback 10000

# View current buffer size
Ctrl+A i

# Clear scrollback buffer
Ctrl+A C  (clears screen but not buffer)

# Set buffer per-session
screen -S work -X scrollback 5000
```

_exec_
```bash
echo "Edit ~/.screenrc to set defscrollback"
```

_output_
```bash
Edit ~/.screenrc to set defscrollback
```

Configure and manage scrollback buffer size.

- Larger buffers use more memory
- 10000 lines is good default for most work
- Per-window scrollback available in newer screen

**Best practices:**

- Set scrollback to 10000 for normal development work
- Search scrollback regularly to find past commands
- Clear scrollback when debugging sensitive information

**Common errors:**

- **pageup not working in copy mode**: May be bound to different key, check with Ctrl+A ?

## Advanced Commands

Advanced screen configuration and automation

### Configuration and Keybindings

Configure screen with ~/.screenrc

**Keywords:** config, keybinding, customize, screenrc, settings

#### Create essential ~/.screenrc configuration

```bash
# ~/.screenrc example
# Increase scrollback buffer
defscrollback 10000

# Set terminal type
term screen-256color

# Enable 256 colors
termcapeinfo xterm-256color 'Co#256:AB=\E[48;5;%dm:AF=\E[38;5;%dm'

# Disable startup message
startup_message off

# Set default window title
shelltitle '$ |bash'

# Automatically detach on hangup
autodetach on

# Enable visual bell
vbell on

# Set the command character
escape ^Aa
```

_exec_
```bash
cat ~/.screenrc | head -15
```

_output_
```bash
defscrollback 10000
term screen-256color
startup_message off
```

Configure screen with common settings in ~/.screenrc.

- ~/.screenrc is sourced when screen starts
- Settings apply to all new screen sessions
- Changes require restarting screen to take effect
- Some settings can be overridden per-session

#### Custom keybindings configuration

```bash
# ~/.screenrc - custom keybindings
# Create new window (override default)
bind c new-window

# Vim-style navigation
bind h select -1
bind l select +1
bind j prev
bind k next

# Alt+number for windows
bind '^[1' select 1
bind '^[2' select 2
bind '^[3' select 3

# Custom split bindings
bind | split -v
bind - split

# Reload config
bind r source ~/.screenrc 'Reload complete'
```

_exec_
```bash
echo "Add bindings to ~/.screenrc"
```

_output_
```bash
Add bindings to ~/.screenrc
```

Create custom keybindings matching your preferred workflow.

- Control characters use format ^X (Ctrl+X)
- Meta (Alt) characters use format ^[
- Test new bindings before making permanent

**Best practices:**

- Start with minimal ~/.screenrc and add gradually
- Use consistent keybinding patterns across tools
- Document non-obvious bindings in config file

**Common errors:**

- **unknown command in screenrc**: Check syntax with 'screen -c ~/.screenrc' before committing

### Automation and Scripting

Automate screen with shell commands and scripts

**Keywords:** automate, script, command, send-keys, batch

#### Automate session creation with scripts

```bash
#!/bin/bash
# Create automated development environment
SESSION="dev"

# Create session with first window
screen -S "$SESSION" -d -m

# Create and name windows
screen -S "$SESSION" -X new-window -t "editor"
screen -S "$SESSION" -X new-window -t "build"
screen -S "$SESSION" -X new-window -t "monitor"

# Send initial commands
screen -S "$SESSION" -p "editor" -X send-keys "vim" Enter
screen -S "$SESSION" -p "build" -X send-keys "cd ~/project" Enter

# Attach to session
screen -r "$SESSION"
```

_exec_
```bash
echo "Script automates session setup"
```

_output_
```bash
Script automates session setup
```

Automate screen session setup with shell scripts.

- -p option specifies target window
- send-keys sends keystrokes to session
- Can chain multiple commands in script
- Useful for standardizing team workflows

#### Send commands to running session

```bash
# Send commands to unnamed session
screen -S mysession -X send-keys "ls -la" Enter

# Send to specific window
screen -S mysession -p 2 -X send-keys "npm test" Enter

# Send without Enter (for typing)
screen -S dev -X send-keys "git status"

# Run monitoring command
#!/bin/bash
while true; do
  screen -S monitor -X send-keys "clear" Enter
  date | screen -S monitor -X send-keys -
  sleep 10
done
```

_exec_
```bash
echo "Use -X send-keys for automation"
```

_output_
```bash
Use -X send-keys for automation
```

Send commands to active or background sessions remotely.

- Useful for deployment and monitoring automation
- Can integrate with cron for scheduled tasks
- Combine with pipes for complex workflows

**Best practices:**

- Create templates for common session setups
- Log session activity for automation tracking
- Use descriptive window names in scripts

**Common errors:**

- **broken pipe when sending to session**: Verify session exists with screen -ls

## Tips and Tricks

Best practices and productivity tips

### Best Practices and Workflows

Recommended patterns for effective screen usage

**Keywords:** best, practices, tips, workflow, productivity

#### Organize projects into sessions

```bash
# Create sessions for different projects
screen -S frontend -d
screen -S backend -d
screen -S devops -d

# Each session contains logical windows
# frontend session
screen -S frontend -X new-window -t "editor"
screen -S frontend -X new-window -t "dev-server"
screen -S frontend -X new-window -t "tests"

# backend session
screen -S backend -X new-window -t "api"
screen -S backend -X new-window -t "database"
screen -S backend -X new-window -t "logs"

# List all project sessions
screen -ls | grep -E '(frontend|backend|devops)'
```

_exec_
```bash
echo "Use sessions for projects, windows for tasks"
```

_output_
```bash
Use sessions for projects, windows for tasks
```

Organize work into sessions by project with task-specific windows.

- Sessions isolate different projects
- Windows organize tasks within a project
- Easy to switch context without losing state
- Works well for polyglot development

#### Monitor multiple servers from one session

```bash
# Create monitoring session
screen -S servers -d

# Create windows for each server
for server in web db cache load; do
  screen -S servers -X new-window -t "$server"
  screen -S servers -p "$server" -X send-keys \
    "ssh user@${server}.example.com" Enter
done

# Create summary window
screen -S servers -X new-window -t "summary"

# Monitor all with watch command
screen -S servers -p summary -X send-keys \
  "watch -n 5 'for s in web db cache load; do echo $s; ssh user@${s} uptime; done'" Enter
```

_exec_
```bash
echo "Use same session for related monitoring"
```

_output_
```bash
Use same session for related monitoring
```

Monitor multiple systems from one session with separate windows.

- One session per environment reduces context switching
- Windows allow monitoring different aspects
- Good for sysadmin and DevOps workflows

**Best practices:**

- One session per major project or environment
- [object Object]
- Detach before closing terminal to preserve sessions
- Reattach to same session for consistency

**Common errors:**

- **lost my session after terminal closed**: Never kill terminal - always detach first with Ctrl+A d

### Common Workflows

Ready-to-use patterns for typical tasks

**Keywords:** workflow, pattern, example, common, ready

#### Web development workflow

```bash
#!/bin/bash
# Web development setup
SESSION="web"
screen -S "$SESSION" -d -m

# Window 0: Code editor
screen -S "$SESSION" -X new-window -t "editor"
screen -S "$SESSION" -p "editor" -X send-keys "cd ~/projects/myapp && vim" Enter

# Window 1: Dev server
screen -S "$SESSION" -X new-window -t "server"
screen -S "$SESSION" -p "server" -X send-keys "cd ~/projects/myapp && npm start" Enter

# Window 2: Tests
screen -S "$SESSION" -X new-window -t "test"
screen -S "$SESSION" -p "test" -X send-keys "cd ~/projects/myapp && npm test" Enter

# Window 3: Git/shell
screen -S "$SESSION" -X new-window -t "shell"
screen -S "$SESSION" -p "shell" -X send-keys "cd ~/projects/myapp && bash" Enter

# Attach to session
screen -r "$SESSION"
```

_exec_
```bash
echo "Save as startup script for web projects"
```

_output_
```bash
Save as startup script for web projects
```

Create a standardized web development environment.

- Saves time on setup for new projects
- Ensures consistent window organization
- Easy to extend with more tools

#### System administration quick reference

```bash
# Quick reference for sysadmins
# Session per environment:
screen -S prod   # Production monitoring
screen -S staging  # Staging environment
screen -S dev    # Development/testing

# In each session, split regions for:
# - Top: Monitoring (top, htop, watch)
# - Bottom-left: Logs (tail -f logfile)
# - Bottom-right: Services (systemctl commands)

# Workflow in session:
Ctrl+A S           # Split horizontally
Ctrl+A c           # Create window in top
Ctrl+A Tab         # Move to bottom
Ctrl+A |           # Split vertically
Ctrl+A c           # Create window bottom-left
Ctrl+A Tab         # Move bottom-right
Ctrl+A c           # Create window bottom-right

# Load baseline services in background
screen -d -m "systemctl status"
```

_exec_
```bash
echo "Sysadmin can leverage splits for complex monitoring"
```

_output_
```bash
Sysadmin can leverage splits for complex monitoring
```

Organize server management tasks efficiently with splits.

- Splits allow monitoring multiple aspects simultaneously
- Useful for complex troubleshooting
- Saves window switching time during incidents

**Best practices:**

- Create template scripts for repetitive setups
- Save 3-5 most useful session templates
- Document any non-obvious shortcuts

**Common errors:**

- **commands don't run in automation script**: Add delays with sleep between send-keys calls
