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: tmux if-shell runs a tmux command only when a shell test passes

Tmux
~/tips/tip-tmux-if-shell

if-shell 'test "$(uname)" = Darwin' 'set -g status-style bg=blue' 'set -g status-style bg=green'

Runs a tmux command only if a shell test succeeds, so one config works on many machines.

My tmux config would be neater if one file worked on both my Mac and a Linux box. tmux can branch on a shell command, so one file can adapt itself.

According to the manual, if-shell runs a shell command with /bin/sh and executes the first tmux command if it returns success, or the second one otherwise. The else command is optional:

if-shell 'test "$(uname)" = Darwin' 'set -g status-style bg=blue' 'set -g status-style bg=green'

The synopsis is if-shell [-bF] [-t target-pane] shell-command command [command]. With -b the shell command runs in the background, so tmux does not wait for it. With -F the shell command is not executed at all: the text counts as success if, after formats are expanded, it is neither empty nor zero. That suits a check on a tmux format:

if-shell -F '#{==:#{session_name},work}' 'set -g status-style bg=red'

Braces let you write several commands in the second argument:

if-shell 'test -f ~/.tmux.local.conf' {
  source-file ~/.tmux.local.conf
}

That loads a local override only if the file exists, so a missing file does not print an error on start.

The caveat is quoting. The manual explains that some commands parse their arguments to create a new command, so arguments can be parsed twice or more: once by tmux and once by the command itself. Nested quotes get messy quickly. I keep the test short, or put it in a small script and call that. Also, if-shell stops the commands after it in the queue until the shell command finishes, unless you use -b.

Further reading: tmux manual (if-shell)

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