tmux
by itself starts a new session, tmux attach
attaches to a previous session.
tmux attach
will fail if there is no previous session.
These two facts combine to give the following solution:
tmux attach || tmux
It tries tmux attach
first, and if it fails, runs tmux
by itself. This attaches to the previous session if there is one, and starts a new session if there isn't. So that's the first part.
For the second part, you want this code to run every time you log in via SSH. So you need to check:
- whether it is a login shell. This can be done using
shopt -q login_shell
.
- whether you are connected via SSH. This can be done by checking if
$SSH_CLIENT
is set, i.e.: [ -n "$SSH_CLIENT" ]
.
So you should add this to the end of your .bashrc
:
if shopt -q login_shell && [ -n "$SSH_CLIENT" ]; then
tmux attach || tmux
fi
shux() { ssh "$1" -t tmux a -d ;}
... – jasonwryan Sep 14 '15 at 1:11