This is kind of a hastle. The correct way to do this within tmux (not relying on an external shell script) combines features of both Vincent and jdloft's responses.
The if-shell
command in tmux is used as
if-shell [-bF] [-t target-pane] shell-command command [command]
(alias: if)
Execute the first command if shell-command returns success or the second command otherwise. Before
being executed, shell-command is expanded using the rules specified in the FORMATS section, including
those relevant to target-pane. With -b, shell-command is run in the background.
If -F is given, shell-command is not executed but considered success if neither empty nor zero (after
formats are expanded).
Note that tmux shell-command expansion will expand variables of the form #{pane_current_path}
but otherwise will leave the command alone.
More importantly, note that tmux uses /bin/sh -c
to execute the shell command we specify. Thus, the command must be POSIX compliant, so tests of the form [[
are not guaranteed to be portable. Modern Ubuntu and Debian systems, for example, symlink /bin/sh
to dash
.
We want to run a POSIX compliant shell command that tests the tmux version and returns 0 (true) if the desired version is found.
if-shell '[ $(echo "$(tmux -V | cut -d" " -f2) >= 2.1" | bc) -eq 1 ]' \
'command if true' \
'command if false'
Example:
if-shell '[ $(echo "$(tmux -V | cut -d" " -f2) >= 2.1" | bc) -eq 1 ]' \
'set -g mouse on; set -g mouse-utf8 on' \
'set -g mode-mouse on; set -g mouse-resize-pane on; set -g mouse-select-pane on; set -g mouse-select-window on'
This correctly deals with the fact that we are doing floating point arithmetic, so bc
is required. Additionally, there is no need for an if/then/else/fi construct, as the [
operator produces a truthy value by itself.
A couple notes
- Lines continuing onto the next line cannot have trailing comments or tmux will give an "unknown command" error message.
- The "command if false" can be omitted.
- Multiple commands for either true or false can be combined using
;
- The command is run on the underlying shell using
/bin/sh -c
. Other approaches that use [[
or other non-POSIX syntax are not guaranteed to work.
EDIT: A previous version of this answer used [[
, which doesn't work on systems that don't use bash. Replacing with [
solves this.
[[ ]]
and(( ))
in that test? I would think just(( ))
would be enough assumingif
(which isif-shell
?) tests the return code.if "(( $(tmux -V | cut -c 6-) < 2.1 ))" "set -g mode-mouse on; set -g mouse-resize-pane on; set -g select-pane on; set -g select-window on"
fixes the problem, Can you post your comment as an answer.(( ))
can't handle the decimal numbers so if that works it is a different reason (or accidental). Does tmux have a way to test for features? (I assume you only want that turned on in versions that support it.)