LoginSignup
6
3

More than 5 years have passed since last update.

mintty * tmux で、開発サーバにssh接続した際に自動的に背景色を変える

Last updated at Posted at 2017-07-29

コマンドを実行するホストを間違ってしまったときの恐怖。。。

今接続しているのって開発サーバだっけ?ステージングサーバだっけ?本番だっけ?
ターミナルを複数起動しているときってドキドキしませんか?僕はします。

きちんと接続先ホストや実行するコマンドを確認すれば問題ないんですがやっぱり不安です。
僕は普段mintty * tmuxで作業するのでウィンドウ名を自動的に切り替えることで誤操作をなくそうとしていました。

ただこの方法だと以下の問題が有り正直使いにくいです。
1. ウィンドウ名がそんなに目立たない
image_20170730_050355.jpg
2. 同一ウィンドウで複数ペインを起動している場合にわけがわからない
左側は本番環境。右側はローカル環境ですがウィンドウ名は「本番環境」となっています。
image_20170730_050525.jpg

ウインドウ名ではなくもっと目立って、ペイン単位の何かの情報を変更しよう

背景色を変えてみようと思います。ドキュメントにもしっかりやり方が載っていますね。
http://man.openbsd.org/OpenBSD-current/man1/tmux.1#select-pane

The colour is one of: black, red, green, yellow, blue, magenta, cyan, white, aixterm bright variants (if supported: brightred, brightgreen, and so on), colour0 to colour255 from the 256-colour set, default, or a hexadecimal RGB string such as ‘#ffffff’, which chooses the closest match from the default 256-colour set.

こんな感じでかんたんに背景色が変更できます。
tmux select-pane -P 'bg=Red'
各々の環境の文字色に合わせて見やすい色を探すことをオススメします。

sshで接続したときに自動的に背景色を変える

~/.bashrc
function ssh() {
    # tmux起動時
    if [[ -n $(printenv TMUX) ]] ; then
        # 現在のペインIDを退避
        local pane_id=$(tmux display -p '#{pane_id}')
        # 接続先ホスト名に応じて背景色を切り替え
        if [[ `echo $1 | grep '\.production\.'` ]] ; then
            tmux select-pane -P 'bg=colour52,fg=white'
        elif [[ `echo $1 | grep '\.staging\.'` ]] ; then
            tmux select-pane -P 'bg=colour58,fg=white'
        elif [[ `echo $1 | grep '\.dev\.'` ]] ; then
            tmux select-pane -P 'bg=colour95,fg=white'
        fi

        # 通常通りssh続行
        command ssh $@

        # デフォルトの背景色に戻す
        tmux select-pane -t $pane_id -P 'default'
    else
        command ssh $@
    fi
}

sshで接続する際のホスト名に、開発環境の場合は.dev.、ステージング環境の場合は.staging.、本番環境の場合は.production.という文字列を含むようにしているのでそれに合わせてif文で処理を分けます。
いろいろ試した結果こんな色に落ち着きました。指定している色の値は↑のコードをご確認ください。

image_20170801_001141.jpg

6
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
6
3