Scripting Reference
Ready-to-use tmux scripting patterns. Copy, adapt, and run.
Idempotent Session Start (Safest Pattern)
#!/bin/bash
SESSION="mywork"
# Attach if already running; create if not
tmux has-session -t "$SESSION" 2>/dev/null \
&& tmux attach -t "$SESSION" \
&& exit 0
# Create and configure
tmux new -s "$SESSION" -n "shell" -d
tmux attach -t "$SESSION"
Multi-Window Setup
#!/bin/bash
SESSION="dev"
tmux has-session -t "$SESSION" 2>/dev/null && tmux attach -t "$SESSION" && exit
tmux new -s "$SESSION" -n "editor" -d
tmux new-window -t "$SESSION" -n "server"
tmux new-window -t "$SESSION" -n "logs"
tmux new-window -t "$SESSION" -n "git"
# Commands per window
tmux send-keys -t "$SESSION:server" "npm run dev" Enter
tmux send-keys -t "$SESSION:logs" "tail -f ./logs/app.log" Enter
# Start on editor window
tmux select-window -t "$SESSION:editor"
tmux attach -t "$SESSION"
Multi-Pane Layout (Monitoring Grid)
#!/bin/bash
SESSION="monitor"
tmux has-session -t "$SESSION" 2>/dev/null && tmux attach -t "$SESSION" && exit
tmux new -s "$SESSION" -n "grid" -d
tmux split-window -h -t "$SESSION:grid"
tmux split-window -v -t "$SESSION:grid.0"
tmux split-window -v -t "$SESSION:grid.1"
tmux select-layout -t "$SESSION:grid" tiled
tmux send-keys -t "$SESSION:grid.0" "htop" Enter
tmux send-keys -t "$SESSION:grid.1" "tail -f /var/log/syslog" Enter
tmux send-keys -t "$SESSION:grid.2" "watch -n 5 df -h" Enter
tmux send-keys -t "$SESSION:grid.3" "watch -n 5 free -h" Enter
tmux attach -t "$SESSION"
Send a Command to All Panes
#!/bin/bash
SESSION="work"
WINDOW="logs"
# Get all pane IDs in a window
PANES=$(tmux list-panes -t "$SESSION:$WINDOW" -F "#P")
for PANE in $PANES; do
tmux send-keys -t "$SESSION:$WINDOW.$PANE" "clear" Enter
done
Wait for a File to Appear (Build Watcher)
#!/bin/bash
SESSION="build"
tmux new -s "$SESSION" -d "make all && touch /tmp/build-done"
while ! [ -f /tmp/build-done ]; do
echo "Waiting for build..."
sleep 10
done
rm /tmp/build-done
echo "Build complete"
tmux attach -t "$SESSION"
Config Snippet: Common Bindings
~/.tmux.conf
# Prefix
unbind C-b
set -g prefix C-a
bind C-a send-prefix
# Reload
bind r source-file ~/.tmux.conf \; display "Reloaded!"
# Splits that remember current path
bind | split-window -h -c "#{pane_current_path}"
bind - split-window -v -c "#{pane_current_path}"
# Vim navigation
bind h select-pane -L
bind j select-pane -D
bind k select-pane -U
bind l select-pane -R
# Repeatable resize
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
# Mouse
set -g mouse on
# Vi copy mode
setw -g mode-keys vi
bind-key -T copy-mode-vi v send-keys -X begin-selection
bind-key -T copy-mode-vi y send-keys -X copy-selection-and-cancel
# Large history
set -g history-limit 50000
# 256 color
set -g default-terminal "screen-256color"
# Base index 1
set -g base-index 1
setw -g pane-base-index 1
set -g renumber-windows on
# No escape delay (important for vim)
set -g escape-time 0