Table of Contents

Tmux Scripting

Scripting with tmux lets you automate session setup. Launch sessions with tmux new-session, create windows with tmux new-window, and send commands with tmux send-keys. This is useful for project-specific startup routines.

Basic session creation:

$ tmux new-session -d -s work          # create detached session (no attach)
$ tmux new-session -s work -c ~/proj   # create session in directory
$ tmux attach -t work                  # attach to session when ready

Send commands to a window:

$ tmux send-keys -t work "npm start" Enter
$ tmux send-keys -t work:1 "npm test" Enter  # window 1

Create windows and panes:

$ tmux new-window -t work -n build -c ~/build
$ tmux split-window -t work:build -v -c ~/build

Example startup script

#!/bin/bash
# dev-setup.sh: create a project layout
 
SESSION="dev"
PROJECT_DIR="$HOME/myproject"
 
# Create session
tmux new-session -d -s $SESSION -c $PROJECT_DIR
 
# Editor window
tmux send-keys -t $SESSION "nvim" Enter
 
# Test window
tmux new-window -t $SESSION -n test -c $PROJECT_DIR
tmux send-keys -t $SESSION:test "npm test" Enter
 
# Build window
tmux new-window -t $SESSION -n build -c $PROJECT_DIR
tmux split-window -t $SESSION:build -v
tmux send-keys -t $SESSION:build.0 "npm run watch" Enter
 
# Attach to the first window
tmux attach -t $SESSION

Run it:

$ bash dev-setup.sh

Clean up:

$ tmux kill-session -t dev

Common patterns:

Use tmux list-sessions to check if a session exists before creating it:

tmux has-session -t work 2>/dev/null || tmux new-session -d -s work

This pattern is useful in scripts to avoid errors if the session already exists.