3
3

More than 5 years have passed since last update.

tmuxで「ssh接続時」「ssh切断時」に対象windowを指定した上で、自動でwindow名を変更する

Last updated at Posted at 2016-12-15

上記の記事を参考に私の環境でも設定を行ってみたのですが、window名がうまく復元できない場合がありました。

以下のようなケース(window名については適当です)

  1. windowを複数(window1,window2)を開いている
    • window1は「ECサイト開発」、window2は「Androidアプリ開発」というwindow名を設定しておく
  2. window1で開発用サーバへssh接続
    • window1が「dev_server0001」というwindow名に切り替わる
  3. window2に切り替えて別の作業
  4. タイムアウトが原因でwindow1のsshがいつの間にか切断されている
    • window1は「dev_server0001」のままで、window2が「ECサイト開発」というwindow名に切り替わる

理想の動き

4のタイミングでこうなるのが理想です。

  • 操作しているwindowはwindow2だが、window1のwindow名が「ECサイト開発に戻る

いろいろ試行錯誤

renameする対象windowを指定することが出来ないかなーと公式のマニュアルを見てみる。

rename-windowコマンド

なにやら使えそうなオプションを発見。tmux rename-window -tで指定できそう
http://man.openbsd.org/OpenBSD-current/man1/tmux.1

rename-window [-t target-window] new-name
(alias: renamew)
Rename the current window, or the window at target-window if specified, to new-name.

display-messageコマンド

dispalyってaliasだったんですね。
http://man.openbsd.org/OpenBSD-current/man1/tmux.1

display-message [-p] [-c target-client] [-t target-pane] [message]

(alias: display)
Display a message. If -p is given, the output is printed to stdout, otherwise it is displayed in the target-client status line. The format of message is described in the FORMATS section; information is taken from target-pane if -t is given, otherwise the active pane for the session attached to target-client.

更に引数でどの情報を表示するのか?を指定できるらしい。
http://man.openbsd.org/OpenBSD-current/man1/tmux.1#FORMATS

window_id Unique window ID
window_name #W Name of window

ということはtmux display -p '#{window_id}'でwindow_idを退避しておけば、window名復元時に対象を指定できるはず!!

上記調査を基に.bashrcを修正

.bashrc
# ssh接続、切断時にtmuxウィンドウ名を動的に変更する
function ssh() {
        # tmux起動時
        if [[ -n $(printenv TMUX) ]]
        then
                # 現在のwindow名を退避
                local window_name=$(tmux display -p '#{window_name}' )
                local window_id=$(tmux display -p '#{window_id}' )
                # 通常通りssh続行
                command ssh $@
                # 退避していたwindow名を復元
                tmux rename-window -t $window_id $window_name
        else
                command ssh $@
        fi
}

これで理想の動きを実現できました。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3