Terminal Multiplexers: tmux and GNU Screen
Master terminal multiplexers to enhance productivity with split windows, persistent sessions, and synchronized commands across multiple terminals, with practical examples and automation scripts.
Terminal Multiplexers: tmux and GNU Screen
A comprehensive guide to terminal multiplexing with tmux and GNU Screen, including advanced usage patterns, automation scripts, and practical workflows for system administrators and developers.
Overview
Terminal multiplexers are powerful tools that allow you to work with multiple terminal sessions within a single window. They are essential for remote server management, complex development workflows, and any scenario where you need to run multiple terminal commands simultaneously.
This guide covers two of the most popular terminal multiplexers:
- tmux (Terminal Multiplexer) - A modern, feature-rich terminal multiplexer
- GNU Screen - The classic terminal multiplexer with a long history
We'll also explore a specialized script called tmux-multiple
that simplifies working with multiple synchronized sessions.
Basic Concepts
Sessions, Windows, and Panes
Both tmux and Screen organize your terminal workspace using a hierarchy:
- Sessions: Independent terminal instances that can be detached and reattached
- Windows: Virtual terminals within a session (like tabs in a browser)
- Panes: Split views within a window (horizontal or vertical divisions)
This organization allows you to:
- Run multiple commands simultaneously
- Monitor multiple processes
- Switch between different tasks easily
- Preserve your terminal state across network disconnections
tmux Basics
tmux Installation
# On Debian/Ubuntu sudo apt install tmux # On macOS with Homebrew brew install tmux # On CentOS/RHEL sudo yum install tmux
Basic tmux Commands
| Command | Description | |------------------------------|------------------------------| | tmux | Start a new session | | tmux new -s name | Start a new named session | | tmux ls | List all sessions | | tmux attach -t name | Attach to a named session | | tmux detach (or Ctrl+b d) | Detach from current session | | tmux kill-session -t name | Kill a named session |
tmux Key Bindings
All tmux commands are prefixed with Ctrl+b
by default:
| Key Binding | Action | |---------------|--------------------------------------------------| | Ctrl+b c | Create a new window | | Ctrl+b n | Move to the next window | | Ctrl+b p | Move to the previous window | | Ctrl+b % | Split the current pane vertically | | Ctrl+b " | Split the current pane horizontally | | Ctrl+b arrow | Navigate between panes | | Ctrl+b z | Toggle pane zoom (full-screen) | | Ctrl+b [ | Enter copy mode (use vi or emacs keys to navigate) |
GNU Screen Basics
Screen Installation
# On Debian/Ubuntu sudo apt install screen # On macOS with Homebrew brew install screen # On CentOS/RHEL sudo yum install screen
Basic Screen Commands
| Command | Description | |----------------------|----------------------------------| | screen | Start a new session | | screen -S name | Start a new named session | | screen -ls | List all sessions | | screen -r name | Attach to a named session | | screen -d -r name | Detach and reattach to a session | | exit or Ctrl+d | Exit the current screen |
Screen Key Bindings
All Screen commands are prefixed with Ctrl+a
by default:
| Key Binding | Action | |---------------|--------------------------------------| | Ctrl+a c | Create a new window | | Ctrl+a n | Move to the next window | | Ctrl+a p | Move to the previous window | | Ctrl+a S | Split the current region horizontally| | Ctrl+a \| | Split the current region vertically | | Ctrl+a tab | Switch between regions | | Ctrl+a d | Detach from the session | | Ctrl+a A | Rename the current window |
Advanced tmux Features
Synchronized Panes
One of the most powerful features of tmux is the ability to send the same commands to multiple panes simultaneously:
# While in tmux, toggle synchronization Ctrl+b :setw synchronize-panes on # To turn it off Ctrl+b :setw synchronize-panes off
This is incredibly useful for:
- Managing multiple servers simultaneously
- Running the same commands on different environments
- Comparing outputs from different systems
Custom Configuration
Create a ~/.tmux.conf
file to customize your tmux environment:
# Example tmux.conf # Change the prefix key to Ctrl+a (like screen) set -g prefix C-a unbind C-b bind C-a send-prefix # Enable mouse mode set -g mouse on # Start window numbering at 1 set -g base-index 1 # Increase scrollback buffer size set -g history-limit 10000 # Customize the status bar set -g status-bg black set -g status-fg white
Session Management
# Save tmux sessions using tmux-resurrect Ctrl+b Ctrl+s # Save Ctrl+b Ctrl+r # Restore
Advanced GNU Screen Features
Multiuser Sessions
Screen allows multiple users to share a session:
# Enable multiuser mode Ctrl+a :multiuser on # Grant permission to another user Ctrl+a :acladd username
Screen Logging
# Start logging the current window Ctrl+a H
Custom Configuration
Create a ~/.screenrc
file to customize your Screen environment:
# Example screenrc # Set a large scrollback buffer defscrollback 10000 # Display a status bar hardstatus alwayslastline hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B} %d/%m %{W}%c %{g}]' # Skip the startup message startup_message off # Enable mouse scrolling termcapinfo xterm* ti@:te@
tmux-multiple Script
The tmux-multiple
script is a powerful tool for creating and managing multiple tmux panes with synchronized commands. It's especially useful for:
- Managing multiple servers
- Running the same command across different files
- Executing database queries across multiple databases
Script Overview
#!/bin/bash # tmux-multiple # Author: Mehmet Ali ERGUT # https://github.com/memnuniyetsizim/tmux-multiple
This script simplifies creating multiple tmux panes and optionally synchronizing commands across them.
Usage
# Basic syntax bash tmux-multiple.sh -t "SESSION_NAME" -c "COMMAND" -p "PARAM1;PARAM2;PARAM3" # With synchronized panes bash tmux-multiple.sh -g -t "SESSION_NAME" -c "COMMAND" -p "PARAM1;PARAM2;PARAM3"
Parameters
-t
: Session title/name-c
: Command to run in each pane (optional)-p
: Parameters separated by semicolons (one for each pane)-g
: Enable synchronized panes (send commands to all panes)-i
: Install the script with tmux configuration-h
: Display help
Script Examples
Example 1: Edit multiple files simultaneously
bash tmux-multiple.sh -g -t "editConfig" -c "vim" -p "/etc/nginx/nginx.conf;/etc/hosts;/etc/ssh/sshd_config"
This creates a tmux session named "editConfig" with three panes, each running vim with a different configuration file. The -g
flag enables synchronized panes, so your keystrokes are sent to all panes simultaneously.
Example 2: Monitor multiple log files
bash tmux-multiple.sh -t "logs" -c "tail -f" -p "/var/log/syslog;/var/log/auth.log;/var/log/nginx/error.log"
This creates a session with three panes, each tailing a different log file.
Example 3: Connect to multiple servers
bash tmux-multiple.sh -t "servers" -c "ssh" -p "user@server1;user@server2;user@server3"
This creates a session with three panes, each connecting to a different server.
How the Script Works
The script:
- Creates a new tmux session with the specified name
- Splits the window into multiple panes based on the parameters
- Runs the specified command with each parameter in its respective pane
- Arranges the panes in a tiled layout
- Optionally enables synchronized input across all panes
Implementation Details
The core functionality relies on tmux's ability to create new panes and send commands:
# Create a new session tmux new-session -d -s $sessionname # For each parameter, create a new pane and run the command for i in $parameters do tmux split-window -v -t $sessionname "$runcommand $i" tmux select-layout tiled done # Enable or disable synchronized panes if [ "$sync" != "" ]; then tmux set-window-option synchronize-panes on else tmux set-window-option synchronize-panes off fi
Compatibility Note
This script was developed for older versions of tmux and may require modifications for the latest versions. Key changes in newer tmux versions include:
- Mouse mode configuration changes
- Synchronize-panes syntax updates
- Window and pane indexing behavior
Implementing Similar Functionality with GNU Screen
While the tmux-multiple
script is designed for tmux, similar functionality can be achieved with GNU Screen using a custom script:
#!/bin/bash # screen-multiple.sh usage() { echo "Usage: screen-multiple.sh -s SESSION_NAME -c COMMAND -p PARAM1,PARAM2,PARAM3" echo " -s: Screen session name" echo " -c: Command to run (optional)" echo " -p: Parameters separated by commas" exit 1 } # Parse arguments while getopts "s:c:p:" opt; do case $opt in s) session=$OPTARG ;; c) command=$OPTARG ;; p) params=$OPTARG ;; *) usage ;; esac done # Check required parameters if [ -z "$session" ] || [ -z "$params" ]; then usage fi # Create a new screen session screen -dmS "$session" # Convert comma-separated parameters to array IFS=',' read -ra PARAM_ARRAY <<< "$params" # For each parameter, create a new window and run the command window=0 for param in "${PARAM_ARRAY[@]}"; do if [ -z "$command" ]; then screen -S "$session" -X screen $window "$param" else screen -S "$session" -X screen $window "$command $param" fi ((window++)) done # Attach to the session screen -r "$session"
Using the Screen Script
# Example: Edit multiple files ./screen-multiple.sh -s "config_edit" -c "vim" -p "/etc/hosts,/etc/nginx/nginx.conf,/etc/ssh/sshd_config" # Example: Monitor logs ./screen-multiple.sh -s "logs" -c "tail -f" -p "/var/log/syslog,/var/log/auth.log,/var/log/nginx/error.log"
Practical Use Cases
Remote Server Management
Terminal multiplexers are invaluable for managing remote servers:
- Persistent Sessions: Keep your work running even if your connection drops
- Multiple Tasks: Monitor logs while editing configuration files
- Synchronized Commands: Apply the same changes across multiple servers
Development Workflows
For developers, terminal multiplexers offer:
- Split Workspace: Run your code in one pane, edit in another, and monitor output in a third
- Multiple Services: Start database, backend, and frontend servers in separate panes
- Testing: Run tests in one pane while coding in another
Database Administration
Database administrators can benefit from:
- Multiple Connections: Connect to different databases simultaneously
- Query Comparison: Run the same query against development and production
- Monitoring: Watch logs and performance metrics while making changes
Performance and Resource Considerations
tmux vs Screen
| Feature | tmux | GNU Screen | |-----------------|------------------------|--------------------------| | Memory Usage | Generally lower | Slightly higher | | CPU Usage | Efficient | Efficient | | Feature Set | More modern features | More stable, fewer features | | Customization | Extensive | Good | | Scripting | Excellent | Good | | Compatibility | Newer systems | Works on almost anything |
When to Choose Each
-
Choose tmux when:
- You need advanced features like synchronized panes
- You want a more modern, actively developed tool
- You need better window/pane management
-
Choose Screen when:
- You need maximum compatibility with older systems
- You prefer simplicity over features
- You need multiuser capabilities
Best Practices
- Use Named Sessions: Always name your sessions descriptively
- Create Aliases: Set up aliases for common tmux/screen commands
- Use Configuration Files: Customize your environment with
.tmux.conf
or.screenrc
- Learn Key Bindings: Memorize the most common key combinations
- Script Repetitive Tasks: Use scripts like
tmux-multiple
for common workflows
Conclusion
Terminal multiplexers like tmux and GNU Screen are essential tools for anyone who works extensively in the command line. They enhance productivity, enable complex workflows, and provide resilience against network disconnections.
The tmux-multiple
script demonstrates how these tools can be extended and automated to handle even more complex scenarios. Whether you're managing multiple servers, working with various configuration files, or monitoring different processes, terminal multiplexers provide the flexibility and power you need.
By mastering these tools, you'll significantly improve your efficiency and capabilities in terminal environments.
References
Technologies Used
Other
Have a project in mind?
Let's work together to bring your ideas to life. Our team of experts is ready to help you build something amazing.