tmux.confの設定内容を端末のOSによって変える

設定内容を端末のOSによって変える

設定ファイルの条件文について使い慣れた形式で記載する方法の解説が見当たらなかったので書いておきたいと思います。

version

$tmux -V
tmux 3.2a

マニュアルを見てみると以下のように書いてあります。

$man tmux

 Commands may be parsed conditionally by surrounding them with ‘%if’, ‘%elif’, ‘%else’ and ‘%endif’.  The argument to ‘%if’ and ‘%elif’ is expanded as a format (see FORMATS) and if it evaluates to false (zero or empty), subsequent text is ignored until the
   closing ‘%elif’, ‘%else’ or ‘%endif’.  For example:

   %if "#{==:#{host},myhost}"
   set -g status-style bg=red
   %elif "#{==:#{host},myotherhost}"
   set -g status-style bg=green
   %else
   set -g status-style bg=blue
   %endif

 Will change the status line to red if running on ‘myhost’, green if running on ‘myotherhost’, or blue if running on another host.  Conditionals may be given on one line, for example:

   %if #{==:#{host},myhost} set -g status-style bg=red %endif

つまり以下のように設定することができます。

.tmux.conf

%if "$(uname | grep Linux)"
  ### for Linux (Ubuntu)
  bind -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "xsel -ip && xsel -op | xsel -ib"
  bind -T copy-mode-vi Enter send-keys -X copy-pipe-and-cancel "xsel -ip && xsel -op | xsel -ib"
  bind ] run 'tmux set-buffer -- "$(xsel -b)"; tmux paste-buffer'
%else
  ### for Mac
  bind -T copy-mode-vi y send-keys -X copy-pipe-and-cancel "pbcopy"
  bind -T copy-mode-vi Enter send-keys -X copy-pipe-and-cancel "pbcopy"
%endif

例ではunameの結果によってクリップボード共有の設定を変えています。

かんたんな説明

シェルの終了ステータスを条件にしています。

grepした結果見つかった場合に0が返ってくるのでこれを利用して読み込む設定を変えています。

Ubuntuで確認してみます(fish)

$uname | grep Linux
Linux #見つかったので0(正常終了)

$uname | grep Darwin
[0|1]$ #unameは正常終了、grepは見つからなかったので1を返す

bashであればこのように確認することができます

$ ls
work

$ ls | grep work
work
$ echo $?
0

$ ls | grep test
$ echo $?
1