特定のホストにSSHしたときに色を変える

プロダクション環境にログインしたときなど、注意したいときのために、iTerm2の背景色を変える方法について。

元ネタ: https://gist.github.com/956095

さらに、Terminal向けの元ネタがどこかにあったはずなので、Terminalでも同様のことができる。

元ネタではスクリプト化しているが、管理が面倒なので.zshrcで済ませてしまう。
また、スクリプト内にホスト名などを埋め込みたくないので、 別ファイルにして管理する。

.zshrcに以下の関数を定義

if [[ x$TERM_PROGRAM = xiTerm.app ]]; then
  set_term_bgcolor(){
    local R=$1
    local G=$2
    local B=$3
    /usr/bin/osascript <<EOF > /dev/null 2>&1
tell application "iTerm"
  tell the current terminal
    tell the current session
      set background color to {$(($R*65535/255)), $(($G*65535/255)), $(($B*65535/255))}
    end tell
  end tell
end tell
EOF
  }
  
  is_production() {
    if [[ -f ~/.production_hosts ]]; then
      for i in `cat ~/.production_hosts`; do
        if [[ "$@" =~ $i ]]; then
          return 0
        fi
      done
    fi
    return 1
  }

  is_staging() {
    if [[ -f ~/.staging_hosts ]]; then
      for i in `cat ~/.staging_hosts`; do
        if [[ "$@" =~ $i ]]; then
            return 0
        fi
      done
    fi
    return 1
  }

  ssh_color() {
    if is_production "$@"; then
        set_term_bgcolor 40 0 0
    elif is_staging "$@"; then
        set_term_bgcolor 0 10 40
    fi
    ssh $@
    set_term_bgcolor 0 0 0
  }

  alias ssh=ssh_color
  compdef _ssh ssh_color=ssh
fi

次に、 .production_hosts に対象ホスト名を記載。

.production_hosts

.example.co.jp
www.example.com

.staging_hosts も同様に作成する。

以上。

compdef の行は、aliasでzshの補完を効かせるために必要。