3

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.

4 Answers 4

8

You can use tmux detach -P.

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

3
  • 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
4

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.

2
  • 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
2

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

1
  • 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
1

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

You must log in to answer this question.

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