sshtmux

How to automatically start tmux on SSH session?


I have ten or so servers that I connect to with SSH on a regular basis. Each has an entry in my local computer's ~/.ssh/config file.

To avoid losing control of my running process when my Internet connection inevitably drops, I always work inside a tmux session. I would like a way to have tmux automatically connect every time an SSH connection is started, so I don't have to always type tmux attach || tmux new after I SSH in.

Unfortunately this isn't turning out to be as simple as I originally hoped.


Solution

  • Alright, I found a mostly satisfactory solution. In my local ~/.bashrc, I wrote a function:

    function ssh () {/usr/bin/ssh -t "$@" "tmux attach || tmux new";}
    

    which basically overwrites the ssh terminal function to call the built-in ssh program with the given arguments, followed by "tmux attach || tmux new".

    (The $@ denotes all arguments provided on the command line, so ssh -p 123 user@hostname will be expanded to ssh -t -p 123 user@hostname "tmux attach || tmux new")

    (The -t argument is equivalent to RequestTTY Force and is necessary for the tmux command.)