brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a small shell script builds your tmux session with all windows

Tmux
~/tips/tip-tmux-session-startup-script

tmux has-session -t "$S" 2>/dev/null && exec tmux attach -t "$S"

Recreates the same windows, panes and commands with one command.

Setting up the same windows every morning gets old. tmux commands work fine from a shell script, so I’d let a script do it.

#!/bin/sh
S=site
tmux has-session -t "$S" 2>/dev/null && exec tmux attach -t "$S"
tmux new-session -d -s "$S" -n code -c ~/projects/site
tmux split-window -h -t "$S:code" -c ~/projects/site
tmux new-window -t "$S" -n logs -c ~/projects/site
tmux send-keys -t "$S:logs" 'tail -f logs/app.log' Enter
tmux select-window -t "$S:code"
exec tmux attach -t "$S"

The first line after the name checks whether the session exists and simply attaches if it does, so running the script twice is safe. Otherwise it creates the session detached with -d, splits the first window, opens a log window, types a command into it and attaches at the end.

The -t "$S:code" targets matter. Without them a detached session can’t know which window you mean, and commands may land in the wrong place.

send-keys types into the pane as if you did it, which means the shell must be ready. On a slow login shell the first keys can arrive early, so keep the commands simple.

From inside tmux, attach refuses to nest a session in a pane. If you run the script there, swap the last line for tmux switch-client -t "$S".

Further reading: tmux manual page (OpenBSD)

More Tmux tips tmux new -d -s report -x 200 -y 50 'top' tmux wait-for build-done set -g allow-passthrough on tmux kill-server Ctrl-b [ All Tmux tips (125) All topics

Link