LoginSignup
7
5

More than 5 years have passed since last update.

tmuxで自動アタッチ & デタッチ時に自動exit

Posted at

ssh先などでtmuxを使ってる場合、毎回アタッチしたり、デタッチした後にexitを打ったりするのはだるいですよね。
なので、これらを自動的に行う設定を書いてみました。

if [[ -n "${REMOTEHOST}${SSH_CONNECTION}" && -z "$TMUX" && -z "$STY" ]]; then
    function confirm {
        MSG=$1
        while :
        do
            echo -n "${MSG} [Y/n]: "
            read ans
            if [ -z "$ans" ]; then
                ans="y"
            fi
            case $ans in
                [yY]) return 0 ;;
                [nN]) return 1 ;;
            esac
        done
    }
    option=""
    if tmux has-session && tmux list-sessions; then
        echo "tmux attached session "
        option="attach"
    else
        echo "tmux created new session"
    fi
    tmux $option && confirm "exit?" && exit
fi

上記のコードを.zshrcなどに書いておくと、sshで繋いだ時に自動的にtmuxが起動します。
また、デタッチしたとき以下のような表示が出て、yを入力するとexitが実行されます。

exit? [Y/n]:

デフォルトでyが入力されるようになっているので、デタッチ後にエンターを押せばsshも切れるという感じです。
tmuxの外で作業したい場合や、tmuxがうまく動かなくなることも想定して、confirmを使ってexitするかどうかを決めれるようにしています。

7
5
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
7
5