Detach from tmux session and close ssh session with 1 command

Frequently I want to exit my ssh session without also killing the tmux session I am using. To do this I have to run the following commands:

tmux detach
exit

or alternatively use the shortcut Ctrl+B D and then exit.

Is there a way to streamline this into one command? I’ve tried using an alias but it seems to execute both commands inside the tmux session.

Asked By: Adam Griffiths

||

Instead of automating the deconnection, I would change the connection. I’m guessing you currently connect using SSH, then run tmux attach; if you combine both steps,

 ssh -t user@host tmux attach

the SSH session becomes tied to the lifetime of the attaching tmux process, rather than the initial shell, and detaching from tmux will automatically close the SSH connection.

Answered By: Stephen Kitt

You can use tmux detach -P.

Or use ~. to exit ssh (which will detach tmux because its tty disappears).

Answered By: Nicholas Marriott

Unless your setup is too weird, you can kill the SSH connection with Enter ~ . (all separate keypresses). The tmux session should become detached (like with any other SSH disconnection).

Answered By: muru

Automatically start tmux on ssh connection. Logout on detach.
by thelinuxkid does exactly what OP asks, entirely within bash:

This bit automatically opens tmux when ssh’ing into a server. 
If a session does not exist a new one is created. 
Otherwise, the last session is attached. 
This should always be run last either in .bashrc or as a script in .bashrc.d. 
The user is logged out from the server on detach.

# This should always be run last either in .bashrc or as a script in .bashrc.d
if [[ -z "$TMUX" ]]; then
    tmux has-session &> /dev/null
    if [ $? -eq 1 ]; then
      exec tmux new
      exit
    else
      exec tmux attach
      exit
    fi
fi
Answered By: user533798
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.