Available for day contractsFrom 21st September I have availability for day and half day contracts. Please contact for more information.

Contact →
mikepreston.org

Tmux

Terminal multiplexer for managing multiple terminal sessions within a single window.

Tmux

Terminal multiplexer for managing multiple terminal sessions within a single window.

Overview

Tmux (Terminal Multiplexer) allows you to create, access, and control multiple terminals from a single screen. It's essential for DevOps workflows, remote server management, and maintaining persistent sessions that survive disconnections. Sessions can be detached and reattached, making it ideal for long-running processes on remote servers.

Tmux ServerSession: devWindow 1: serverPane 0Window 0: editorPane 0Pane 1Window 0: editorWindow 1: serverWindow 2: logsSession: devSession: prodTerminal 1Terminal 2Tmux ServerSession: devWindow 1: serverPane 0Window 0: editorPane 0Pane 1Window 0: editorWindow 1: serverWindow 2: logsSession: devSession: prodTerminal 1Terminal 2

The hierarchy is: Server > Session > Window > Pane

  • Server: Background process managing all sessions
  • Session: Collection of windows, can be detached/attached
  • Window: Full-screen container within a session (like tabs)
  • Pane: Split section within a window

Session Management

Sessions are the top-level containers in tmux. They persist on the server until explicitly killed.

Key Concepts

  • Sessions run independently on the tmux server
  • Multiple clients can attach to the same session
  • Sessions survive terminal disconnection
  • Each session has a name for easy identification

Common Commands

# Create new session
tmux new-session -s mysession
tmux new -s mysession

# Create session with specific window name
tmux new -s mysession -n mywindow

# Create detached session
tmux new -d -s background-job

# List all sessions
tmux list-sessions
tmux ls

# Attach to session
tmux attach -t mysession
tmux a -t mysession

# Attach to last session
tmux attach
tmux a

# Detach from current session (from inside tmux)
# Prefix + d

# Kill session
tmux kill-session -t mysession

# Kill all sessions except current
tmux kill-session -a

# Kill all sessions except named
tmux kill-session -a -t mysession

# Rename session
tmux rename-session -t old-name new-name

# Switch to another session (from inside tmux)
# Prefix + s (session list)
# Prefix + ( (previous session)
# Prefix + ) (next session)

Examples

# Development workflow: create project session
tmux new -s myproject -n code -d
tmux send-keys -t myproject:code 'cd ~/projects/myproject && vim' Enter
tmux new-window -t myproject -n server
tmux send-keys -t myproject:server 'npm run dev' Enter
tmux attach -t myproject

# Check if session exists before creating
tmux has-session -t mysession 2>/dev/null || tmux new-session -d -s mysession

Window Management

Windows act like tabs within a session, each providing a full terminal screen.

Key Concepts

  • Windows are numbered starting from 0
  • Each window can have a custom name
  • One window is active at a time per client
  • Windows can be moved between sessions

Common Commands

# Key bindings (after Prefix)
# c     - Create new window
# ,     - Rename current window
# &     - Kill current window (with confirmation)
# n     - Next window
# p     - Previous window
# 0-9   - Switch to window by number
# l     - Toggle to last active window
# w     - Window list (interactive)
# f     - Find window by name

# Command line
tmux new-window -t mysession
tmux new-window -t mysession -n mywindow

# Create window with command
tmux new-window -t mysession 'htop'

# Rename window
tmux rename-window -t mysession:0 newname

# Kill window
tmux kill-window -t mysession:1

# Move window
tmux move-window -s mysession:1 -t othersession:

# Swap windows
tmux swap-window -s 1 -t 3

# Link window from another session
tmux link-window -s othersession:1 -t mysession

# Select window
tmux select-window -t mysession:2

Examples

# Create multiple windows for a project
tmux new-session -s project -n editor -d
tmux new-window -t project -n terminal
tmux new-window -t project -n logs
tmux new-window -t project -n database
tmux select-window -t project:editor
tmux attach -t project

# Renumber windows to fill gaps
tmux move-window -r

Pane Management

Panes split windows into multiple viewable areas, allowing side-by-side terminals.

Key Concepts

  • Panes divide a window horizontally or vertically
  • Each pane runs an independent shell
  • Panes can be resized, swapped, and zoomed
  • Layouts can be automatically arranged
Complex LayoutPane 0Pane 1Pane 2Vertical SplitPane 0Pane 1Horizontal SplitPane 0Pane 1Complex LayoutPane 0Pane 1Pane 2Vertical SplitPane 0Pane 1Horizontal SplitPane 0Pane 1

Common Commands

# Key bindings (after Prefix)
# %         - Split horizontally (left/right)
# "         - Split vertically (top/bottom)
# x         - Kill current pane (with confirmation)
# o         - Cycle through panes
# q         - Show pane numbers (press number to jump)
# z         - Toggle pane zoom (fullscreen)
# {         - Swap pane with previous
# }         - Swap pane with next
# Space     - Cycle through layouts
# Arrow     - Navigate to pane in direction
# Ctrl+Arrow - Resize pane (hold Prefix)

# Resize panes
# Prefix + Alt + Arrow keys (resize by 5 cells)
# Or use resize-pane command

# Command line
tmux split-window -h          # Horizontal split
tmux split-window -v          # Vertical split
tmux split-window -h -l 30%   # 30% width for new pane (-p 30 on tmux <3.1)

# Resize pane
tmux resize-pane -D 10        # Down 10 cells
tmux resize-pane -U 10        # Up 10 cells
tmux resize-pane -L 10        # Left 10 cells
tmux resize-pane -R 10        # Right 10 cells
tmux resize-pane -Z           # Toggle zoom

# Select pane
tmux select-pane -t 1
tmux select-pane -L           # Left
tmux select-pane -R           # Right
tmux select-pane -U           # Up
tmux select-pane -D           # Down

# Kill pane
tmux kill-pane -t 1

# Swap panes
tmux swap-pane -s 1 -t 2

# Break pane to new window
tmux break-pane

# Join pane from another window
tmux join-pane -s :1 -t :2

# Select layout
tmux select-layout even-horizontal
tmux select-layout even-vertical
tmux select-layout main-horizontal
tmux select-layout main-vertical
tmux select-layout tiled

Examples

# Create development layout
tmux new-session -s dev -d
tmux split-window -h -p 40
tmux split-window -v -p 50 -t 1
tmux select-pane -t 0
tmux attach -t dev

# Result: Large left pane (60%), two stacked right panes (40%)

# Send command to specific pane
tmux send-keys -t dev:0.1 'tail -f /var/log/syslog' Enter

Copy Mode and Scrolling

Copy mode allows scrolling through terminal history and copying text.

Key Concepts

  • Copy mode uses vi or emacs key bindings (configurable)
  • Text is copied to tmux's internal buffer or system clipboard
  • Multiple buffers can store different copied content
  • Supports searching through scrollback

Common Commands

# Key bindings (after Prefix)
# [         - Enter copy mode
# ]         - Paste from buffer

# In copy mode (vi keys - requires "setw -g mode-keys vi"; default is emacs)
# q         - Exit copy mode
# Space     - Start selection
# Enter     - Copy selection and exit
# Escape    - Clear selection
# v         - Toggle rectangle selection
# /         - Search forward
# ?         - Search backward
# n         - Next search match
# N         - Previous search match
# g         - Go to top
# G         - Go to bottom
# h,j,k,l   - Navigate (vi style)
# w,b       - Word forward/back
# Ctrl+u    - Half page up
# Ctrl+d    - Half page down

# Command line
tmux copy-mode

# List buffers
tmux list-buffers

# Show buffer contents
tmux show-buffer

# Save buffer to file
tmux save-buffer ~/buffer.txt

# Load file into buffer
tmux load-buffer ~/file.txt

# Paste buffer
tmux paste-buffer

# Delete buffer
tmux delete-buffer -b 0

Examples

# Enable vi copy mode in config
set-window-option -g mode-keys vi

# Enable mouse scrolling
set -g mouse on

# Copy to system clipboard (Linux with xclip)
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "xclip -selection clipboard"

# Copy to system clipboard (macOS)
bind-key -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "pbcopy"

# Increase scrollback history
set -g history-limit 50000

Configuration (.tmux.conf)

Tmux is configured through ~/.tmux.conf, which is loaded on server start.

Key Concepts

  • Configuration file is ~/.tmux.conf or /etc/tmux.conf
  • Changes require reload or server restart
  • Use set for session options, setw for window options
  • Supports conditional configuration and sourcing other files

Common Configuration

# ~/.tmux.conf

# ----- General Settings -----

# Change prefix from Ctrl+b to Ctrl+a
unbind C-b
set -g prefix C-a
bind C-a send-prefix

# Enable mouse support
set -g mouse on

# Set scrollback buffer size
set -g history-limit 50000

# Start window numbering at 1
set -g base-index 1
setw -g pane-base-index 1

# Renumber windows when one is closed
set -g renumber-windows on

# Reduce escape time (important for vim)
set -sg escape-time 10

# Enable true colour support
set -g default-terminal "tmux-256color"
set -ag terminal-overrides ",xterm-256color:RGB"

# ----- Key Bindings -----

# Reload configuration
bind r source-file ~/.tmux.conf \; display "Config reloaded!"

# Split panes with intuitive keys
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
unbind '"'
unbind %

# Navigate panes with vim keys
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R

# Resize panes with vim keys
bind -r H resize-pane -L 5
bind -r J resize-pane -D 5
bind -r K resize-pane -U 5
bind -r L resize-pane -R 5

# Quick window switching
bind -r C-h select-window -t :-
bind -r C-l select-window -t :+

# ----- Copy Mode -----

# Use vi keys in copy mode
setw -g mode-keys vi

# Vi-style copy/paste
bind -T copy-mode-vi v send-keys -X begin-selection
bind -T copy-mode-vi y send-keys -X copy-selection-and-cancel

# ----- Visual Settings -----

# Quiet mode (disable visual bell)
set -g visual-activity off
set -g visual-bell off
set -g visual-silence off
setw -g monitor-activity off
set -g bell-action none

Examples

# Reload config without restarting tmux
tmux source-file ~/.tmux.conf

# Or use the bound key (if configured)
# Prefix + r

# Check current option value
tmux show-options -g prefix
tmux show-window-options -g mode-keys

# Set option from command line
tmux set -g mouse on

Key Bindings

All tmux commands are triggered by a prefix key (default: Ctrl+b) followed by a command key.

Key Concepts

  • Default prefix is Ctrl+b (many users change to Ctrl+a)
  • Bindings can be customised with bind and unbind
  • -r flag makes binding repeatable without prefix
  • -n flag creates binding without prefix

Default Key Bindings Reference

# Session management
Prefix + d     # Detach from session
Prefix + s     # List sessions
Prefix + $     # Rename session
Prefix + (     # Previous session
Prefix + )     # Next session

# Window management
Prefix + c     # Create window
Prefix + ,     # Rename window
Prefix + &     # Kill window
Prefix + n     # Next window
Prefix + p     # Previous window
Prefix + l     # Last window
Prefix + w     # List windows
Prefix + 0-9   # Select window by number
Prefix + f     # Find window

# Pane management
Prefix + %     # Split horizontally
Prefix + "     # Split vertically
Prefix + x     # Kill pane
Prefix + o     # Next pane
Prefix + ;     # Last pane
Prefix + q     # Show pane numbers
Prefix + z     # Toggle zoom
Prefix + {     # Swap pane with previous
Prefix + }     # Swap pane with next
Prefix + Space # Cycle layouts
Prefix + !     # Break pane to window
Prefix + Arrow # Select pane by direction

# Copy mode
Prefix + [     # Enter copy mode
Prefix + ]     # Paste buffer

# Miscellaneous
Prefix + ?     # List key bindings
Prefix + :     # Command prompt
Prefix + t     # Show time

Custom Bindings Examples

# ~/.tmux.conf

# Create binding without prefix
bind -n M-h select-pane -L  # Alt+h to move left

# Create repeatable binding
bind -r Tab select-pane -t :.+  # Tab cycles panes

# Binding with multiple commands
bind b split-window -h \; split-window -v

# Unbind existing key
unbind C-z

# Conditional binding (if running specific command)
bind C-k if-shell "pgrep vim" "send-keys C-k" "select-pane -U"

# Bind to run external command
bind S command-prompt -p "ssh to:" "new-window -n %1 'ssh %1'"

Plugins (TPM)

Tmux Plugin Manager (TPM) simplifies installing and managing tmux plugins.

Key Concepts

  • TPM is the standard plugin manager for tmux
  • Plugins are hosted on GitHub
  • Installed with Prefix + I
  • Updated with Prefix + U

Installation and Setup

# Install TPM
git clone https://github.com/tmux-plugins/tpm ~/.tmux/plugins/tpm

# Add to ~/.tmux.conf
# List of plugins
set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-sensible'
set -g @plugin 'tmux-plugins/tmux-resurrect'
set -g @plugin 'tmux-plugins/tmux-continuum'
set -g @plugin 'tmux-plugins/tmux-yank'

# Initialise TPM (keep at bottom of tmux.conf)
run '~/.tmux/plugins/tpm/tpm'

Common Plugins

# tmux-sensible
# Basic tmux settings everyone can agree on
set -g @plugin 'tmux-plugins/tmux-sensible'

# tmux-resurrect
# Save and restore sessions
set -g @plugin 'tmux-plugins/tmux-resurrect'
# Prefix + Ctrl+s to save
# Prefix + Ctrl+r to restore

# tmux-continuum
# Automatic session saving and restore
set -g @plugin 'tmux-plugins/tmux-continuum'
set -g @continuum-restore 'on'
set -g @continuum-save-interval '15'

# tmux-yank
# Copy to system clipboard
set -g @plugin 'tmux-plugins/tmux-yank'

# tmux-pain-control
# Better pane navigation bindings
set -g @plugin 'tmux-plugins/tmux-pain-control'

# tmux-prefix-highlight
# Highlight when prefix is pressed
set -g @plugin 'tmux-plugins/tmux-prefix-highlight'

# tmux-cpu
# Display CPU/GPU info in status bar
set -g @plugin 'tmux-plugins/tmux-cpu'

# vim-tmux-navigator
# Seamless navigation between vim and tmux panes
set -g @plugin 'christoomey/vim-tmux-navigator'

Plugin Management Commands

# Key bindings
# Prefix + I       Install plugins
# Prefix + U       Update plugins
# Prefix + Alt+u   Uninstall plugins

# Manual installation
~/.tmux/plugins/tpm/bin/install_plugins

# Manual update
~/.tmux/plugins/tpm/bin/update_plugins all

Status Bar Customisation

The status bar displays session information and can be extensively customised.

Key Concepts

  • Status bar has left, centre, and right sections
  • Supports colours, styles, and dynamic content
  • Can display command output and plugin information
  • Position and visibility are configurable

Common Configuration

# ~/.tmux.conf

# ----- Status Bar Position -----
set -g status-position bottom
set -g status-justify left

# ----- Colours -----
# Status bar colours
set -g status-style 'bg=#1e1e2e fg=#cdd6f4'

# Active window
setw -g window-status-current-style 'bg=#89b4fa fg=#1e1e2e bold'
setw -g window-status-current-format ' #I:#W#F '

# Inactive windows
setw -g window-status-style 'bg=#313244 fg=#bac2de'
setw -g window-status-format ' #I:#W#F '

# Pane borders
set -g pane-border-style 'fg=#45475a'
set -g pane-active-border-style 'fg=#89b4fa'

# ----- Content -----
# Left side
set -g status-left-length 40
set -g status-left '#[bg=#f38ba8,fg=#1e1e2e,bold] #S #[default] '

# Right side
set -g status-right-length 100
set -g status-right '#[fg=#a6e3a1]#{?client_prefix,PREFIX ,}#[default]#[bg=#313244] %H:%M #[bg=#89b4fa,fg=#1e1e2e] %d-%b-%Y '

# ----- Variables Reference -----
# #S  Session name
# #I  Window index
# #W  Window name
# #F  Window flags
# #P  Pane index
# #H  Hostname
# #T  Pane title
# #{pane_current_path}  Current directory

Examples

# Minimal status bar
set -g status-left ' #S '
set -g status-right ' %H:%M '
set -g window-status-format ' #I:#W '
set -g window-status-current-format ' #I:#W '

# Show hostname on remote machines
set -g status-right '#H | %H:%M '

# Display battery and CPU (with plugins)
set -g @plugin 'tmux-plugins/tmux-battery'
set -g @plugin 'tmux-plugins/tmux-cpu'
set -g status-right '#{cpu_percentage} | #{battery_percentage} | %H:%M '

# Highlight when in prefix mode
set -g @plugin 'tmux-plugins/tmux-prefix-highlight'
set -g status-right '#{prefix_highlight} | %H:%M '

# Conditional formatting
set -g status-right '#{?window_zoomed_flag,ZOOMED ,}%H:%M '

Useful Shortcuts and Workflows

Development Workflow

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

SESSION="dev"

# Create session with first window
tmux new-session -d -s $SESSION -n editor

# Set up editor window
tmux send-keys -t $SESSION:editor 'cd ~/project && vim' Enter

# Create server window
tmux new-window -t $SESSION -n server
tmux send-keys -t $SESSION:server 'cd ~/project && npm run dev' Enter

# Create logs window with splits
tmux new-window -t $SESSION -n logs
tmux split-window -h -t $SESSION:logs
tmux send-keys -t $SESSION:logs.0 'tail -f /var/log/app.log' Enter
tmux send-keys -t $SESSION:logs.1 'tail -f /var/log/error.log' Enter

# Create database window
tmux new-window -t $SESSION -n db
tmux send-keys -t $SESSION:db 'psql -U postgres' Enter

# Return to editor
tmux select-window -t $SESSION:editor

# Attach to session
tmux attach -t $SESSION

Remote Server Management

# SSH and immediately attach to or create tmux session
ssh user@server -t 'tmux attach -t main || tmux new -s main'

# Run command in existing session
ssh user@server 'tmux send-keys -t main "uptime" Enter'

# Capture pane output remotely
ssh user@server 'tmux capture-pane -t main -p' > output.txt

Synchronised Panes

# Enable synchronised input to all panes
:setw synchronize-panes on

# Or bind to key
bind S setw synchronize-panes

# Useful for running same command on multiple servers
# Split window, SSH to different servers, then synchronise

Quick Commands

# Display large clock
Prefix + t

# Choose window/session interactively
Prefix + w (windows)
Prefix + s (sessions)

# Show all key bindings
Prefix + ?

# Command prompt
Prefix + :

# Swap current pane with next
Prefix + }

# Rotate pane positions
Prefix + Ctrl+o

# Clear pane history
Prefix + :clear-history

Scripting with tmux

# Check if inside tmux
if [ -n "$TMUX" ]; then
    echo "Inside tmux"
fi

# Get current session name
tmux display-message -p '#S'

# Get current window index
tmux display-message -p '#I'

# List all windows in session
tmux list-windows -t session-name -F '#I:#W'

# Capture pane content
tmux capture-pane -p -t target-pane

# Wait for pane to finish command
tmux wait-for -L sync-channel

Quick Reference

Action Command/Binding
New session tmux new -s name
Attach session tmux attach -t name
Detach Prefix + d
List sessions tmux ls
New window Prefix + c
Next/Previous window Prefix + n/p
Select window Prefix + 0-9
Rename window Prefix + ,
Split horizontal Prefix + %
Split vertical Prefix + "
Navigate panes Prefix + Arrow
Zoom pane Prefix + z
Kill pane Prefix + x
Copy mode Prefix + [
Paste Prefix + ]
List bindings Prefix + ?
Command prompt Prefix + :
Reload config tmux source ~/.tmux.conf

Common Issues and Solutions

Issue Solution
Colours not displaying correctly Set TERM=xterm-256color before starting tmux, add set -g default-terminal "tmux-256color" to config
Mouse scrolling not working Add set -g mouse on to .tmux.conf
Escape delay in vim Add set -sg escape-time 10 to .tmux.conf
Copy mode not copying to system clipboard Install xclip (Linux) and configure copy-pipe, or use tmux-yank plugin
Session lost after SSH disconnect Use tmux attach -t session to reconnect; consider tmux-resurrect for persistence
Prefix key conflict Change prefix with set -g prefix C-a (or another key)
New panes/windows start in wrong directory Use -c "#{pane_current_path}" in split/new-window bindings
Status bar not updating Reduce status-interval value: set -g status-interval 5
Plugins not installing Ensure TPM is cloned to ~/.tmux/plugins/tpm, press Prefix + I
Window numbering gaps after closing Add set -g renumber-windows on to config

Related Topics

To complement this tmux cheatsheet, consider exploring these related topics:

  • Vim - Modal text editor that integrates seamlessly with tmux for efficient terminal-based development
  • Bash/zsh - Shell scripting for automating tmux session creation and management
  • Linux CLI - Core command-line utilities used within tmux panes
  • SSH/systemd - Remote server access where tmux sessions are essential for persistence
  • Git - Version control workflows commonly run in tmux windows/panes