Docs · Scripting · API
tmux scripting and API: control tmux from the shell, Python and control mode
tmux has no separate HTTP or socket API: its API is the tmux command itself. Every action you can do with a key is a command a script can run, -F formats turn any state into text you can parse, and control mode (tmux -C) gives programs a live, line-based connection. Libraries such as libtmux for Python wrap the same commands.
On this page
Quick answer
How do I control tmux from a script?
tmux new-session -d -s api -c ~/code/api # create, detached
tmux send-keys -t api 'npm test' Enter # type a command
tmux capture-pane -p -t api -S -50 # read the last 50 lines
tmux display -p -t api '#{pane_current_command}' # query state
tmux list-panes -a -F '#{pane_id} #{pane_current_path}' # list anythingRun these from any shell, inside or outside tmux. For a long-lived connection with live output use control mode; from Python use libtmux.
The command line is the API
A tmux command run from a shell starts a short-lived client, sends the command to the server over its Unix socket, prints any output and exits with status 0 on success or 1 on error. That makes every command scriptable. Four habits make scripts reliable:
- Target precisely.
-t session:window.paneworks, but indexes change withbase-index. Prefer names (api:editor) and ids:$1for sessions,@2for windows,%3for panes. A leading=forces an exact name match (-t =api). The full syntax is in the target reference. - Capture ids on creation.
new-session,new-window,split-windowandnew-paneaccept-P -F '#{pane_id}'and print the id of what they created. - Ask with formats.
display -pprints one format;list-sessions,list-windowsandlist-panestake-Ffor the output and-fto filter. - Check with exit codes.
tmux has-session -t =apireturns 0 if the session exists. Inside tmux,$TMUXis set and$TMUX_PANEholds the current pane id.
tmux display -p -t api '#{session_name}:#{window_index}.#{pane_index} #{pane_id} #{pane_current_command}'
api:0.1 %1 top
tmux list-sessions -F '#{session_name} #{session_windows} windows#{?session_attached, (attached),}'
api 2 windows
logs 1 windows
tmux list-panes -a -F '#{session_name}:#{window_name}.#{pane_index} #{pane_id} #{pane_current_command}'
api:editor.0 %0 bash
api:editor.1 %1 top
api:server.0 %2 bash
logs:bash.0 %3 bash
# filters: every pane running top; windows whose name matches *serv*
tmux list-panes -a -f '#{==:#{pane_current_command},top}' -F '#{pane_id}'
%1
tmux list-windows -a -f '#{m:*serv*,#{window_name}}' -F '#{session_name}:#{window_index} #{window_name}'
api:1 server
# conditionals, comparisons and time formatting
tmux display -p -t api '#{?#{>=:#{session_windows},2},many,few} #{t:session_created}'
many Thu Oct 29 00:58:41 2026tmux display -a lists every format variable with its current value; the 3.8 man page documents more than 250 of them, explained in man tmux: formats.
send-keys: type into a pane
tmux send-keys -t api 'make test' Enter types the text and presses Enter. Arguments that look like key names are sent as keys, everything else as text:
| Command | What reaches the pane |
|---|---|
send-keys -t api 'ls -la' Enter | The text, then the Enter key (C-m is the same key) |
send-keys -t api C-c | Ctrl+C, to interrupt the running program |
send-keys -t api -l 'echo C-c Enter' | Literally echo C-c Enter: -l turns off key-name lookup |
send-keys -t api -N 3 Up | The Up arrow three times |
send-keys -t api -X history-top | A copy mode command (the pane must be in copy mode) |
send-keys -t api -R \; clear-history | Reset the terminal state, then clear the scrollback |
Watch the quoting: the shell removes one level of quotes before tmux sees the text. Text with a leading dash needs --, as in send-keys -t api -- '-v'. A pane that is running a full-screen program receives the keys as if typed, so send q or C-c before typing a new command.
capture-pane: read what is on screen
tmux capture-pane -p -t api # visible screen to stdout
tmux capture-pane -p -t api -S -200 # plus the last 200 lines of history
tmux capture-pane -p -t api -S - -E - # the whole history
tmux capture-pane -p -J -t api -S - # join lines that wrapped
tmux capture-pane -p -e -t api # keep colors (escape sequences)
tmux capture-pane -p -I -t api -S -3 # 3.8: prefix each line with the time it entered history
1793235421 1
1793235421 2
1793235421 3Without -p, the capture goes into a paste buffer instead. -S and -E are line numbers: 0 is the first visible line, negative numbers reach into the history, and - means the start or end. Visible lines that have not scrolled into history yet show 0 with -I. Saving scrollback to a file and logging with pipe-pane are covered in copy mode: capture-pane.
Wait for a command to finish
tmux runs commands in panes asynchronously, so a script needs a signal. Three ways, from most to least portable:
# 1. wait-for channels (any tmux): the pane signals, the script blocks
tmux send-keys -t build 'make test; tmux wait-for -S tests-done' Enter
tmux wait-for tests-done && tmux capture-pane -p -t build -S -20
# 2. Poll the screen for a line
until tmux capture-pane -p -t web | grep -q '^Listening on'; do sleep 0.5; done
# 3. tmux 3.8: run it in a new floating pane and get the exit status back
tmux new-pane -W -d 'make test'; echo "make exited with $?"tmux 3.8 can also wait for events. wait-for -E name blocks until a hook or notification fires; -F adds a condition on its payload and -v prints the payload:
tmux wait-for -v -E pane-exited
event=pane-exited
exit_status=7
exit_success=0
pane=%2
window=@2
# wait only for a pane that exits with an error
tmux wait-for -E -F '#{==:#{exit_success},0}' pane-exitedHooks and 3.8 monitors
Hooks run tmux commands when something happens: set-hook -g pane-exited 'display "pane exited"'. Every command has an after- hook (after-new-window, after-split-window …), and there are about 50 event hooks such as client-attached, pane-died, window-renamed and session-created. tmux 3.8 rebuilt hooks around events with a payload, added hooks such as pane-resized, window-zoomed and client-created, and added three that follow OSC 133 shell-integration marks: pane-shell-prompt, pane-command-started and pane-command-finished.
Payload keys are available to the hook command as #{hook_…} formats. This one logs every command that ran for a second or more, with its exit status:
set-hook -g pane-command-finished "if -F '#{e|>=:#{hook_command_duration},1}' { run-shell 'echo #{hook_pane} exit=#{hook_command_status} after #{hook_command_duration}s >> ~/.tmux-commands.log' }"It needs a shell or prompt that emits OSC 133 marks (shell integration). Tested on tmux 3.8, a 1.2-second command that exited with status 2 logged %0 exit=2 after 1s, and a command that took under a second logged nothing.
Monitors: hooks on any format (set-hook -B)
A monitor checks a format once a second and fires a user hook (name starting with @) when the value changes, or with -T when it becomes true. It uses the same name:what:format syntax as control mode subscriptions, where what is a pane (%0), %* for all panes, a window (@1), @*, or empty for the session.
# fire @idle when pane %0 is back at its shell prompt
tmux set-hook -g -T -B '@idle:%0:#{==:#{pane_current_command},bash}' 'display "build finished"'
tmux show-hooks -g -B
@idle:%0:#{==:#{pane_current_command},bash}
# a script can block on the same event
tmux send-keys -t %0 'make' Enter; sleep 1.5; tmux wait-for -v -E @idle
event=@idle
last=0
pane=%0
session=$0
value=1
window=@0
window_index=0
# fire your own events
tmux set-hook -E @deploy # wakes every "wait-for -E @deploy"
tmux set-hook -g -u -B '@idle' # remove the monitorMonitors sample once a second, so a command shorter than that can finish between checks; for exact signals use wait-for -S or new-pane -W. Monitors are not inherited: they only run in the scope where you set them.
Control mode: tmux -C
Control mode turns a tmux client into a text protocol on stdin and stdout. You write commands as lines; tmux answers each one between %begin and %end (or %error) and, between replies, sends notifications such as pane output. It is how iTerm2 draws tmux windows as native tabs (tmux -CC, explained in iTerm2 and tmux -CC), and it is the fastest way for a program to run many commands and follow output live.
tmux -C attach -t w
%begin 1793248608 315 0
%end 1793248608 315 0
%session-changed $0 w
%window-renamed @0 bash
list-windows
%begin 1793248608 317 1
0: bash* (1 panes) [80x24] [layout b25d,80x24,0,0,0] @0 (active)
%end 1793248608 317 1
send-keys -t w "echo hi" Enter
%begin 1793248608 318 1
%end 1793248608 318 1
%output %0 echo hi\015\012\033[?2004l\015
%output %0 hi\015\012\033[?2004h
%output %0 $
bogus-cmd
%begin 1793248609 319 1
parse error: unknown command: bogus-cmd
%error 1793248609 319 1| Line | Meaning |
|---|---|
%begin time number flags | Start of a reply. number pairs it with its %end; flags is 1 for a command this client sent |
%end / %error | End of a successful or failed reply. Output lines in between may start with % too, so match the number |
%output %pane data | Bytes a pane wrote. Control characters and \ are escaped as octal \ooo |
%window-add, %window-renamed, %layout-change, %session-changed … | State changes, so a client never has to poll |
%subscription-changed | A format you subscribed to with refresh-client -B changed (checked once a second) |
%exit | The client is leaving: detached, killed, or stdin closed |
-C works over pipes. -CC also disables echo; it is what terminal emulators such as iTerm2 use. In 3.8, notifications are never sent inside a %begin/%end block, and control clients receive the old layout format unless they set the new-layouts client flag.
A minimal control mode client in Python
No dependencies. A thread reads stdout and separates replies from notifications; cmd() sends a line and returns that command's output or raises its error.
#!/usr/bin/env python3
"""tmuxctl.py: a minimal tmux control mode (-C) client, no dependencies."""
import queue, re, subprocess, sys, threading
class TmuxControl:
def __init__(self, session="ctl", socket="default"):
self.proc = subprocess.Popen(
["tmux", "-L", socket, "-C", "new-session", "-A", "-s", session],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True,
encoding="utf-8", errors="replace")
self.replies, self.events = queue.Queue(), queue.Queue()
threading.Thread(target=self._reader, daemon=True).start()
self.replies.get() # the reply to new-session itself
def _reader(self):
block = None # (number, lines) while inside %begin
for line in self.proc.stdout:
line = line.rstrip("\n")
word = line.split(" ", 3)
if block is None and word[0] == "%begin":
block = (word[2], [])
elif block and word[0] in ("%end", "%error") and word[2] == block[0]:
self.replies.put((word[0] == "%end", block[1]))
block = None
elif block:
block[1].append(line) # output lines may start with % too
else:
self.events.put(line) # %output, %window-add, %exit ...
def cmd(self, command):
self.proc.stdin.write(command + "\n")
self.proc.stdin.flush()
ok, lines = self.replies.get(timeout=10)
if not ok:
raise RuntimeError("\n".join(lines))
return lines
def close(self):
self.proc.stdin.close() # detaches the control client
self.proc.wait()
def unescape(data):
"""%output escapes control characters and backslash as \\ooo octal."""
return re.sub(r"\\([0-7]{3})", lambda m: chr(int(m.group(1), 8)), data)
if __name__ == "__main__":
tmux = TmuxControl(socket=sys.argv[1] if len(sys.argv) > 1 else "default")
print("version:", tmux.cmd("display-message -p '#{version}'")[0])
pane = tmux.cmd("split-window -P -F '#{pane_id}'")[0]
print("new pane:", pane)
tmux.cmd(f"send-keys -t {pane} 'echo hello from control mode' Enter")
seen = ""
while True: # stream that pane's output
event = tmux.events.get(timeout=10)
if event.startswith(f"%output {pane} "):
seen += unescape(event.split(" ", 2)[2])
if re.search(r"(?<!echo )hello from control mode\r\n", seen):
print("saw output: hello from control mode")
break
try:
tmux.cmd("no-such-command")
except RuntimeError as err:
print("error reply:", err)
tmux.cmd(f"kill-pane -t {pane}")
tmux.close()python3 tmuxctl.py
version: 3.8
new pane: %1
saw output: hello from control mode
error reply: parse error: unknown command: no-such-commandSubscriptions replace polling. Send refresh-client -B 'cmd:%0:#{pane_current_command}' (quote it, or # starts a comment) and tmux reports each change:
%subscription-changed cmd $0 @0 0 %0 : bash
%subscription-changed cmd $0 @0 0 %0 : sleep
%subscription-changed cmd $0 @0 0 %0 : bashPython: libtmux
libtmux is a typed Python wrapper with Server, Session, Window and Pane objects. It runs the tmux CLI underneath and gives you .cmd() on every object for anything it does not wrap. Version 0.62.0 (July 2026) needs Python 3.10+, and its new_pane() creates 3.7+ floating panes. It is still pre-1.0, so pin the version.
python3 -m venv .venv && . .venv/bin/activate
pip install libtmux# workspace.py: a two-pane session built with libtmux (pip install libtmux)
import time
import libtmux
from libtmux.constants import PaneDirection
server = libtmux.Server() # the default server; socket_name="x" is tmux -L x
if server.has_session("api"):
session = server.sessions.get(session_name="api")
else:
session = server.new_session(session_name="api", window_name="dev", attach=False)
editor = session.active_window.active_pane
logs = editor.split(direction=PaneDirection.Right, size="40%")
logs.send_keys("echo ready from libtmux")
time.sleep(0.3)
print([line for line in logs.capture_pane() if line.startswith("ready")])
print(server.cmd("display-message", "-p", "#{version}").stdout)
for pane in session.panes:
print(pane.pane_id, pane.pane_width, pane.pane_current_command)
try:
scratch = editor.new_pane(width=60, height=12) # a floating pane, tmux 3.7+
print("floating:", scratch.pane_floating_flag)
except libtmux.exc.LibTmuxException as err:
print(err)['ready from libtmux']
['3.8']
%0 47 bash
%1 32 bash
floating: 1Other languages and AI agents
Any language that can start a process can drive tmux through the CLI or control mode. These packages exist today (versions from their registries, 28 October 2026):
| Package | Language | Approach | Latest |
|---|---|---|---|
| libtmux | Python | Object API over the CLI; also used by tmuxp | 0.62.0 |
| gotmux | Go | Sessions, windows and panes over the CLI | v0.5.0 |
| tmux_interface | Rust | Typed builders for tmux commands | 0.4.0 |
| tmux-mcp (npm) | MCP server | Lets an AI assistant list sessions, read panes and run commands | 0.2.2 |
MCP servers for AI agents. Several Model Context Protocol servers expose tmux to assistants such as Claude, among them tmux-mcp on npm and Rust and Python projects listed in MCP directories. They all reduce to send-keys and capture-pane, so an agent connected to one can type anything you could. Point it at a dedicated socket (tmux -L agent) rather than your main server. Running agents themselves in tmux is covered in Claude Code and tmux.
Workspace scripts
A workspace script creates a session with every window, pane and command you need, or attaches to it if it already exists. It needs nothing but tmux and a shell.
Create the session detached, if it does not exist
tmux has-session -t "=$SESSION"checks first, so running the script again just reattaches.new-session -dbuilds everything in the background.Add windows and panes, keeping their ids
new-window -P -F '#{pane_id}'andsplit-window -P -F '#{pane_id}'print ids such as%3that you target later. Use-cto start each in the right directory.Start the programs
send-keys -t "$pane" 'npm run dev' Entertypes into each pane, so you keep a shell when the program exits.Attach, or switch if already inside tmux
Check
$TMUX:switch-clientinside tmux,attach-sessionoutside. Attaching from inside fails withsessions should be nested with care.
Full-stack project starter
Save it as start-project.sh, run chmod +x start-project.sh, then ./start-project.sh webapp ~/projects/my-webapp.
#!/usr/bin/env bash
# start-project.sh: build (or reattach to) a full-stack workspace
set -euo pipefail
SESSION="${1:-webapp}"
DIR="${2:-$HOME/projects/my-webapp}"
if ! tmux has-session -t "=$SESSION" 2>/dev/null; then
# Window "code": the editor
tmux new-session -d -s "$SESSION" -n code -c "$DIR"
tmux send-keys -t "=$SESSION:code" 'nvim .' Enter
# Window "services": frontend on top, backend below
front=$(tmux new-window -t "=$SESSION:" -n services -c "$DIR/frontend" -P -F '#{pane_id}')
tmux send-keys -t "$front" 'npm run dev' Enter
back=$(tmux split-window -v -t "$front" -c "$DIR/backend" -P -F '#{pane_id}')
tmux send-keys -t "$back" 'source .venv/bin/activate && uvicorn main:app --reload' Enter
# Window "git-db": database container, then a free shell for git
tmux new-window -t "=$SESSION:" -n git-db -c "$DIR"
tmux send-keys -t "=$SESSION:git-db" 'docker compose up -d postgres' Enter
tmux select-window -t "=$SESSION:code"
fi
# Attach from a normal terminal, or switch if already inside tmux
if [ -n "${TMUX:-}" ]; then
tmux switch-client -t "=$SESSION"
else
tmux attach-session -t "=$SESSION"
fiWhy names and ids instead of numbers? Targets like webapp:1.1 depend on base-index and pane-base-index, which differ between configs. We ran this script on tmux 3.8 (with the default 0-based numbering and with base-index 1) and on 3.4; every run built the same three windows (code, services with two panes, git-db) in the right directories. The trailing colon in -t "=$SESSION:" means "the next free window in that session".
Log monitoring dashboard (2×2 grid)
#!/usr/bin/env bash
# monitor-logs.sh: a 2x2 grid of live logs in one window
set -euo pipefail
SESSION="monitoring"
if ! tmux has-session -t "=$SESSION" 2>/dev/null; then
p1=$(tmux new-session -d -s "$SESSION" -n logs -P -F '#{pane_id}')
p2=$(tmux split-window -h -t "$p1" -P -F '#{pane_id}')
p3=$(tmux split-window -v -t "$p1" -P -F '#{pane_id}')
p4=$(tmux split-window -v -t "$p2" -P -F '#{pane_id}')
tmux send-keys -t "$p1" 'tail -F /var/log/nginx/access.log' Enter
tmux send-keys -t "$p2" 'tail -F /var/log/nginx/error.log' Enter
tmux send-keys -t "$p3" 'journalctl -u postgresql -f' Enter
tmux send-keys -t "$p4" 'htop' Enter
tmux select-pane -t "$p1" -T 'nginx access'
tmux select-pane -t "$p2" -T 'nginx errors'
tmux select-pane -t "$p3" -T 'postgresql'
tmux select-pane -t "$p4" -T 'htop'
tmux select-layout -t "$p1" tiled # even 2x2 grid
tmux set -w -t "$p1" pane-border-status top
tmux set -w -t "$p1" pane-border-format ' #{pane_index}: #{pane_title} '
fi
if [ -n "${TMUX:-}" ]; then
tmux switch-client -t "=$SESSION"
else
tmux attach-session -t "=$SESSION"
fiselect-layout tiled makes the four panes equal. It arranges panes in index order, not in the order you split them, so the script names each pane with select-pane -T and shows the names in the border with pane-border-status top. Tested on tmux 3.8 and 3.4. tail -F keeps following a log after rotation. For AI coding agents, the same pattern runs one agent per pane: see Claude Code and tmux.
tmuxinator vs tmuxp vs smug
Session managers do the same job as a workspace script from a YAML file. Pick one if you prefer declaring layouts to writing shell; stick with a script if you want zero dependencies or conditional logic.
| Shell script | tmuxinator | tmuxp | smug | |
|---|---|---|---|---|
| Language / needs | tmux and a shell | Ruby (gem) | Python 3.10+ (pip) | Go, single binary |
| Config | Bash | YAML (ERB templates) | YAML or JSON | YAML |
| Latest version | – | 3.4.2 (10 Oct 2026) | 1.76.0 (24 Oct 2026) | v0.3.19 (30 Jun 2026) |
| GitHub stars | – | 13.7k | 4.6k | 913 |
| Start / stop | ./start.sh / kill-session | tmuxinator start / stop | tmuxp load / kill-session | smug start / stop |
| Save a running session to a file | No | No | tmuxp freeze | No |
| Import other formats | – | No | tmuxinator, teamocil | No |
| Python API | – | No | libtmux | No |
| Best for | Portable dotfiles, servers, CI | The largest community and most examples | Python users, freezing layouts | A fast binary with no runtime |
Versions from RubyGems, PyPI and the Go module proxy; stars from each GitHub page, 28 October 2026. Teamocil, the fourth classic option, has had no release since 1.4.2 in May 2016; use tmuxp to import its files.
The same workspace in each tool. All three were installed and loaded against tmux 3.8, and each produced a code window and a services window with panes in frontend and backend:
name: webapp
root: ~/projects/my-webapp
windows:
- code: nvim .
- services:
layout: even-vertical
panes:
- cd frontend && npm run dev
- cd backend && uvicorn main:app --reloadgem install tmuxinator
tmuxinator start webapp # or: tmuxinator start -p ./webapp.ymlsession_name: webapp
start_directory: ~/projects/my-webapp
windows:
- window_name: code
panes:
- nvim .
- window_name: services
layout: even-vertical
panes:
- cd frontend && npm run dev
- cd backend && uvicorn main:app --reloadpip install tmuxp
tmuxp load webapp # -d to stay detached
tmuxp freeze webapp # save a running session as YAMLsession: webapp
root: ~/projects/my-webapp
windows:
- name: code
commands:
- nvim .
- name: services
layout: even-vertical
commands:
- cd frontend && npm run dev
panes:
- type: vertical
root: backend
commands:
- uvicorn main:app --reloadgo install github.com/ivaaaan/smug@latest
smug start webapp # smug stop webapp to kill itTo save and restore sessions across reboots instead of declaring them, see tmux-resurrect and tmux-continuum.
Frequently asked questions
How do I create an automated workspace script with tmux?
Write a shell script that checks tmux has-session -t "=name", and if the session is missing creates it with tmux new-session -d -s name -c ~/project, adds windows and panes with new-window and split-window -P -F '#{pane_id}', starts programs with send-keys -t "$pane" 'command' Enter, and finally runs tmux attach -t name (or switch-client when $TMUX is set). The full, tested template is in workspace scripts.
Does tmux have an API?
Not a network or library API. The tmux command line is the API: every command can be run from a script, -F formats return any state as text, and exit codes report success. For a persistent connection there is control mode (tmux -C), a line-based protocol with replies and live notifications. Libraries such as libtmux (Python) wrap these.
How do I send a command to a tmux pane from a script?
Use tmux send-keys -t target 'your command' Enter, for example tmux send-keys -t api:editor.1 'npm test' Enter. Enter (or C-m) presses Return; add -l to send text literally without key-name lookup.
How do I get the output of a tmux pane?
Run tmux capture-pane -p -t target to print the visible screen, add -S - for the full history and -J to join wrapped lines. For live output, use pipe-pane or a control mode client, which receives every %output as it happens.
How do I wait until a command in a tmux pane has finished?
Append a signal to the command and wait for it: tmux send-keys -t build 'make; tmux wait-for -S done' Enter then tmux wait-for done. In tmux 3.8, tmux new-pane -W 'make' waits and returns the exit status, and wait-for -E can wait for events such as pane-exited.
Should I use tmuxinator or tmuxp?
Both start sessions from YAML. tmuxinator (Ruby) has the larger community; tmuxp (Python) can also freeze a running session to a file, import tmuxinator and teamocil configs, and gives you libtmux for scripting. smug is a single Go binary with a similar format. A plain shell script needs no extra runtime at all.
Keep learning
Something wrong or out of date on this page? Email hello@tmux.app and we will fix it.