Skip to content
shellhacks.dev
Command Line

Start tmux with the Same Layout Using a Setup Script

Start the same tmux windows and panes every time with a short script of new-session, new-window, split-window and send-keys calls. Check has-session to reuse one.

2 min read
Summarize in AI

A project needs the same editor window, server window and log pane every day, and you are tired of building them by hand.

Shell
t="tmux -L demo"
$t -f /dev/null kill-server 2> /dev/null
$t -f /dev/null new-session -d -s work -n editor -x 100 -y 30
$t new-window -t work -n server
$t send-keys -t work:server 'echo server started' Enter
$t split-window -h -t work:server
$t send-keys -t work:server.1 'echo logs here' Enter
$t select-window -t work:editor
sleep 0.5
$t list-windows -t work -F '#I:#W panes=#{window_panes}'
$t capture-pane -p -t work:server.1 | grep -c '^logs here$'
$t has-session -t work && echo "second run would see the session and reuse it"
$t kill-server
Text
0:editor panes=1
1:server panes=2
1
second run would see the session and reuse it

new-session -d creates a session without attaching, -n names the first window, new-window and split-window -h add a window and a side-by-side pane, and send-keys ... Enter types a command into a pane. The -t target names a window as session:window and a pane as session:window.index. list-windows -F reports the result, two windows and two panes in the second, and capture-pane -p reads what a pane shows. See the command list in tmux.

A script that creates the session unconditionally fails the second time, so test with has-session -t work and attach instead. send-keys types into a shell that may not be ready yet, and an early command can arrive garbled, so add a short sleep or start the program as the pane's own command. This was run with tmux 3.3a on a private socket.

Share

More snippets

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.