メインコンテンツまでスキップ

Tmux Terminal Multiplexer

Tmux (Terminal Multiplexer) is a powerful command-line tool that allows you to manage multiple terminal sessions within a single window. It's essential for developers, system administrators, and anyone who works extensively with the command line.

Overview

Tmux enables you to:

  • Run multiple programs simultaneously in separate windows and panes
  • Detach and reattach to sessions, maintaining long-running processes
  • Share sessions between multiple users or terminals
  • Organize workflows with custom layouts and configurations
  • Maintain persistent sessions that survive SSH disconnections

Key Concepts

  • Session: A collection of windows managed together
  • Window: A single screen containing one or more panes
  • Pane: Individual terminal instances within a window
  • Prefix Key: Command key combination (default: Ctrl+b)

Installation

Ubuntu/Debian

sudo apt update
sudo apt install tmux

CentOS/RHEL/Fedora

# CentOS/RHEL
sudo yum install tmux

# Fedora
sudo dnf install tmux

macOS

# Using Homebrew
brew install tmux

# Using MacPorts
sudo port install tmux

From Source

# Install dependencies (Ubuntu/Debian)
sudo apt install libevent-dev libncurses-dev build-essential

# Download and compile
git clone https://github.com/tmux/tmux.git
cd tmux
sh autogen.sh
./configure
make && sudo make install

Basic Usage

Starting Tmux

# Start new session
tmux

# Start session with name
tmux new-session -s mysession

# Short form
tmux new -s mysession

# Start with specific command
tmux new-session -s work -c ~/projects

Session Management

# List active sessions
tmux list-sessions
tmux ls

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

# Attach to last session
tmux attach

# Kill session
tmux kill-session -t mysession

# Kill all sessions
tmux kill-server

Detaching from Sessions

# Detach current session
Ctrl+b d

# List sessions and choose one to detach
Ctrl+b D

Window Management

Creating and Managing Windows

CommandAction
Ctrl+b cCreate new window
Ctrl+b ,Rename current window
Ctrl+b &Kill current window
Ctrl+b wList windows (interactive)
CommandAction
Ctrl+b 0-9Switch to window 0-9
Ctrl+b nNext window
Ctrl+b pPrevious window
Ctrl+b lLast window
Ctrl+b fFind window by name

Window Operations

# Create window with name
Ctrl+b c
# Then rename: Ctrl+b ,

# Move window position
Ctrl+b . # Prompts for new index

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

Pane Management

Creating Panes

CommandAction
Ctrl+b %Split horizontally (side by side)
Ctrl+b "Split vertically (top and bottom)
Ctrl+b xKill current pane
CommandAction
Ctrl+b ↑ ↓ ← →Navigate panes
Ctrl+b oNext pane
Ctrl+b ;Last pane
Ctrl+b qShow pane numbers
Ctrl+b q 0-9Go to pane number

Resizing Panes

CommandAction
Ctrl+b Ctrl+↑ ↓ ← →Resize pane
Ctrl+b Alt+↑ ↓ ← →Resize pane (5 cells)
Ctrl+b spaceCycle through layouts

Pane Operations

# Break pane to new window
Ctrl+b !

# Join pane from another window
Ctrl+b :join-pane -s 2.1 # Join pane 1 from window 2

# Swap panes
Ctrl+b { # Swap with previous pane
Ctrl+b } # Swap with next pane

# Synchronize panes (type in all panes)
Ctrl+b :setw synchronize-panes on

Advanced Features

Copy Mode

Tmux includes a powerful copy mode for scrolling and text selection:

# Enter copy mode
Ctrl+b [

# Navigate in copy mode
↑ ↓ ← → # Move cursor
Page Up/Down # Scroll pages
g / G # Go to top/bottom
/ ? # Search forward/backward

# Select and copy text
Space # Start selection
Enter # Copy selection
Ctrl+b ] # Paste

Copy Mode with vi Keys

# Enable vi mode in .tmux.conf
setw -g mode-keys vi

# vi-style copy mode bindings
Ctrl+b [ # Enter copy mode
h j k l # Navigate
v # Start selection (visual mode)
y # Copy selection
Ctrl+b ] # Paste

Session Sharing

# Create shared session
tmux new-session -s shared

# Multiple users attach to same session
tmux attach-session -t shared

# Read-only attachment
tmux attach-session -r -t shared

Scripting and Automation

# Create complex layouts via script
tmux new-session -d -s development
tmux split-window -h
tmux split-window -v
tmux select-pane -t 0
tmux send-keys 'cd ~/project && vim' Enter
tmux select-pane -t 1
tmux send-keys 'cd ~/project && npm start' Enter
tmux select-pane -t 2
tmux send-keys 'cd ~/project && git status' Enter

Configuration

Configuration File

Create ~/.tmux.conf for custom settings:

# Basic configuration example
# Set prefix to Ctrl+a (instead of Ctrl+b)
unbind C-b
set -g prefix C-a
bind C-a send-prefix

# Enable mouse support
set -g mouse on

# Start windows and panes at 1, not 0
set -g base-index 1
setw -g pane-base-index 1

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

# Increase scrollback buffer
set -g history-limit 10000

# Vi mode
setw -g mode-keys vi

# Status bar configuration
set -g status-bg colour235
set -g status-fg colour255
set -g status-left '#S: '
set -g status-right '%Y-%m-%d %H:%M'

# Pane borders
set -g pane-border-style fg=colour240
set -g pane-active-border-style fg=colour166

# Window status
setw -g window-status-current-style fg=colour166,bg=colour235,bold

Advanced Configuration

# Custom key bindings
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R

# Resize panes with vi 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

# Split panes with | and -
bind | split-window -h
bind - split-window -v

# Quick pane cycling
bind -r Tab select-pane -t :.+

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

Plugin Management with TPM

Install Tmux Plugin Manager:

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

# Add to .tmux.conf
set -g @plugin 'tmux-plugins/tpm'
set -g @plugin 'tmux-plugins/tmux-sensible'
set -g @plugin 'tmux-plugins/tmux-resurrect'

# Initialize TPM (add to bottom of .tmux.conf)
run '~/.tmux/plugins/tpm/tpm'

Install plugins: Ctrl+b I
Update plugins: Ctrl+b U
Remove plugins: Ctrl+b Alt+u

Workflow Examples

Development Environment

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

SESSION="development"

# Create session
tmux new-session -d -s $SESSION

# Window 1: Editor
tmux rename-window -t $SESSION:1 'editor'
tmux send-keys -t $SESSION:1 'cd ~/project && vim' Enter

# Window 2: Server
tmux new-window -t $SESSION:2 -n 'server'
tmux send-keys -t $SESSION:2 'cd ~/project && npm start' Enter

# Window 3: Terminal
tmux new-window -t $SESSION:3 -n 'terminal'
tmux send-keys -t $SESSION:3 'cd ~/project' Enter

# Split terminal window
tmux split-window -h -t $SESSION:3
tmux send-keys -t $SESSION:3.2 'cd ~/project && git status' Enter

# Attach to session
tmux attach-session -t $SESSION

Monitoring Setup

# Create monitoring session
tmux new-session -d -s monitoring

# System monitoring
tmux send-keys 'htop' Enter
tmux split-window -h
tmux send-keys 'iotop' Enter
tmux split-window -v
tmux send-keys 'tail -f /var/log/syslog' Enter

# Network monitoring window
tmux new-window
tmux send-keys 'netstat -i 1' Enter
tmux split-window -h
tmux send-keys 'ss -tuln' Enter

Remote Work Session

# Long-running tasks
tmux new-session -d -s remote-work

# Backup process
tmux send-keys 'rsync -av --progress /home/ backup@server:/backups/' Enter

# Log monitoring
tmux split-window -h
tmux send-keys 'tail -f /var/log/application.log' Enter

# Detach and disconnect
tmux detach

Keyboard Shortcuts Reference

Session Commands

CommandAction
Ctrl+b sList sessions
Ctrl+b $Rename session
Ctrl+b dDetach session
Ctrl+b DChoose session to detach

Window Commands

CommandAction
Ctrl+b cCreate window
Ctrl+b ,Rename window
Ctrl+b &Kill window
Ctrl+b wList windows
Ctrl+b n/pNext/Previous window
Ctrl+b 0-9Select window 0-9
Ctrl+b lLast window

Pane Commands

CommandAction
Ctrl+b %Split horizontal
Ctrl+b "Split vertical
Ctrl+b xKill pane
Ctrl+b oNext pane
Ctrl+b ;Last pane
Ctrl+b ↑ ↓ ← →Navigate panes
Ctrl+b spaceCycle layouts
Ctrl+b zZoom pane

Copy Mode Commands

CommandAction
Ctrl+b [Enter copy mode
qExit copy mode
SpaceStart selection
EnterCopy selection
Ctrl+b ]Paste

Troubleshooting

Common Issues

Tmux Not Starting

# Check if tmux is installed
which tmux

# Check version
tmux -V

# Start with verbose output
tmux -v new-session

Configuration Issues

# Validate configuration
tmux source-file ~/.tmux.conf

# Start with default configuration
tmux -f /dev/null new-session

# Check for syntax errors
tmux show-messages

Session Recovery

# List all tmux processes
ps aux | grep tmux

# Kill stuck tmux server
tmux kill-server

# Recover from crash
tmux new-session -d -s recovery
tmux list-sessions

Performance Issues

# Reduce history limit
set -g history-limit 1000

# Disable mouse if causing issues
set -g mouse off

# Check for problematic plugins
tmux show-environment

Debugging

# Start tmux with debugging
tmux -v -f ~/.tmux.conf new-session

# Show current options
tmux show-options -g
tmux show-window-options -g

# Display messages
tmux display-message "Debug info: #{session_name}"

Integration with Other Tools

SSH Integration

# Auto-attach to tmux on SSH
# Add to ~/.bashrc or ~/.zshrc
if [[ -n "$SSH_TTY" ]] && [[ -z "$TMUX" ]]; then
tmux attach-session -t ssh_session || tmux new-session -s ssh_session
fi

Git Integration

# Show git branch in status bar
set -g status-right '#(cd #{pane_current_path}; git rev-parse --abbrev-ref HEAD 2>/dev/null)'

Vim Integration

# Smart pane switching between vim and tmux
# Add to ~/.vimrc
if exists('$TMUX')
function! TmuxOrSplitSwitch(wincmd, tmuxdir)
let previous_winnr = winnr()
silent! execute "wincmd " . a:wincmd
if previous_winnr == winnr()
call system("tmux select-pane -" . a:tmuxdir)
endif
endfunction

nnoremap <silent> <C-h> :call TmuxOrSplitSwitch('h', 'L')<cr>
nnoremap <silent> <C-j> :call TmuxOrSplitSwitch('j', 'D')<cr>
nnoremap <silent> <C-k> :call TmuxOrSplitSwitch('k', 'U')<cr>
nnoremap <silent> <C-l> :call TmuxOrSplitSwitch('l', 'R')<cr>
endif

Best Practices

Session Organization

  1. Use descriptive session names:

    tmux new-session -s "project-frontend"
    tmux new-session -s "monitoring-prod"
  2. Create session templates:

    # Save as tmux-dev-template.sh
    tmux new-session -d -s development
    tmux split-window -h
    tmux split-window -v
    tmux send-keys -t 0 'vim' Enter
    tmux send-keys -t 1 'npm start' Enter
    tmux send-keys -t 2 'git status' Enter
  3. Use consistent window naming:

    tmux rename-window "editor"
    tmux rename-window "server"
    tmux rename-window "logs"

Performance Optimization

# Optimize for large sessions
set -g history-limit 5000
set -s escape-time 0
set -g display-time 1000
set -g status-interval 5

Security Considerations

# Restrict socket permissions
set -g @socket-mode '0600'

# Lock session after inactivity
set -g lock-after-time 1800
set -g lock-command 'vlock'

Resources and References

Productivity Tips
  • Create custom scripts for common session layouts
  • Use tmux with SSH for persistent remote sessions
  • Combine with screen sharing for collaborative debugging
  • Set up automatic session restoration with tmux-resurrect
  • Use mouse mode for easier pane management when learning
Quick Start
  1. Install tmux: sudo apt install tmux
  2. Start session: tmux new -s mysession
  3. Split panes: Ctrl+b % (horizontal) Ctrl+b " (vertical)
  4. Navigate: Ctrl+b ↑ ↓ ← →
  5. Detach: Ctrl+b d
  6. Reattach: tmux attach -t mysession