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

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.

4 Answers 4


You can use tmux detach -P.

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

  • tmux detach -P did the trick for me thanks! Commented Oct 15, 2019 at 8:29
  • I still ending up in the hosts bash session
    – alper
    Commented May 14, 2021 at 20:06
  • this works but it also closes the ssh session to the machine on which tmux was running.
    – krishna
    Commented Sep 20, 2021 at 7:49

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.

  • Thanks for your answer, it doesn't help me because of my particularly weird setup, but I'm sure it will help others. Commented Oct 15, 2019 at 8:11
  • Hopefully someone else will come up with an approach which will also work for you! Commented Oct 15, 2019 at 8:16

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).

  • Yea, I've seen this one but I like to enter commands at the command line rather than using escape sequences :> Commented Oct 15, 2019 at 8:29

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
      exec tmux attach

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .