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.
~/.bashrc
on the servers because I only want it for SSH sessions, not local sessions, and I would prefer to only set it up once.tmux attach || tmux new
to the ~/.ssh/rc
on the servers simply results in the error not a terminal
being thrown after connection, even when the RequestTTY force
option is added to the line for that server in my local SSH config file.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.)