Tmux exit current session, not Tmux itself
When accessing remote servers that I am responsible for, I always initiate a tmux session along with the SSH session. This means I am always in a tmux session and I will never forget to start a tmux session manually. There is something particurly frustrating about starting a process on a remote server only to realise that you I forgot to start a tmux session and the process is going to take > 1 hour. I have to ensure my SSH session remains open, which isn’t always easy if I’m moving around.
I did write a short post recently on how to achieve a tmux session with every SSH session but the next problem is when it comes to exit the SSH session when I’m done - I don’t want it to actually close the tmux session, I want it to close the SSH session but leave the tmux session intact and running.
The solution is incredibly simple.
exit() {
if [[ -z $TMUX ]]; then
builtin exit
else
tmux detach
fi
}
The above function should be added to your .bashrc
file (or .zsh
) and then you need to run source ~/.bashrc
for it to take effect. Remember that this function needs to be on the remote server, not your local workstation.
Now when we are inside a tmux session and we type exit
the SSH session will close but the tmux session will remain ready for us to reconnect later on.