Formats: #{...} variables and conditionals

tmux · Advanced · 12 min

Formats are how scripts ask tmux questions and how you build an informative status bar.

A format is a string with #{variable} placeholders that tmux expands. Hundreds of variables exist: session_name, window_index, window_name, pane_index, pane_id (stable ids like %3), pane_current_path, pane_current_command, pane_pid, client_prefix, window_zoomed_flag...

Where formats are used:

  • display-message -p '#{...}' prints a format for the current pane: the standard way for a script to ask "where am I?".
  • list-sessions, list-windows, list-panes take -F format; -a lists across all sessions. Combine with -f filter to select.
  • Options such as status-left, status-right, window-status-format and the -c of split-window are expanded as formats.

Formats have operators:

  • Conditionals: #{?client_prefix,PREFIX,} shows text only while the prefix is pressed; #{?window_zoomed_flag,[Z],}.
  • Comparisons: #{==:#{pane_current_command},vim}, #{m:*.log,#{pane_title}} (glob match).
  • Modifiers: #{=10:pane_title} truncates, #{b:pane_current_path} is the basename, #{t:...} formats a timestamp.

In status options, %H:%M style strftime codes are also expanded, and #[fg=yellow] sets styles. Use stable ids (%3, @2, $1) rather than indexes in scripts: indexes change as windows are moved or renumbered.

Example

tmux display -p '#{session_name}:#{window_index}.#{pane_index}'   # dev:1.0
tmux display -p '#{pane_current_path}'                           # /home/me/code
tmux list-panes -a -F '#{pane_id} #{session_name} #{pane_current_command}'
# %0 dev vim
# %1 dev node
tmux list-panes -a -f '#{==:#{pane_current_command},node}' -F '#{pane_id}'
# ~/.tmux.conf
set -g status-right '#{?client_prefix,#[reverse]PREFIX#[noreverse] ,}#{b:pane_current_path} %H:%M'
setw -g window-status-current-format '#I:#W#{?window_zoomed_flag, [Z],}'

Remember

  • display -p and list-* -F print formats for scripts
  • #{?cond,yes,no}, #{==:a,b}, #{b:path} and other operators
  • Prefer stable ids (%pane, @window, $session) over indexes in scripts

Watch out for

  • Using single-character aliases like #W without knowing them; the long #{window_name} form is clearer.

Check yourself

  1. How does a script print the current pane's working directory?
  2. What does `#{?window_zoomed_flag,[Z],}` render for an unzoomed window?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: man.openbsd.org/tmux.1#FORMATS