I use ssh to connect to remote server. On a local and a remote machine tmux starts automaticaly on bash start.

Is there a way to detach tmux on local machine before start tmux session on remote?


Not all my remote machines start tmux. I need the trick only for that ones that started i.e. i would like to save tmux session on local machine if remote not start one.

1 Answer 1


You could make a script that uses detach -E to detach and run ssh, something like:


if [ -n "$TMUX" ]; do
   tmux detach -E "ssh \"$@\""
   ssh "$@"

You could run it directly or alias it to ssh.

Note this will not work if you want to pass flag arguments to ssh though.

  • It can be improved to support multiple arguments to ssh, but it's not trivial to do this in a secure manner. The option-argument after -E will be interpreted by a shell, this requires pre-processing $@ to get proper quoting and make sure command injection or such cannot occur. If the interpreter (in the shebang) was bash then this would probably work: -E "ssh ${@@Q}". The Q operator provides the value(s) quoted in a format that can be reused as input. The syntax is not portable. If the script is used as a wrapper for ssh then it should check if it's not being used in a pipe. Nov 22, 2019 at 11:15
  • Thank you for answer! Please, see update
    – dann
    Nov 22, 2019 at 11:32
  • 1
    There is no way for something on your local machine (where tmux is running) to know whether the remote machine is going to start tmux or not unless it always does, or you somehow tell it. Similarly, there is no way for the remote machine to detach a local tmux and even if it did, that would also detach the ssh running inside that tmux. It is impossible to do what you are asking fully automatically. You either need to use different scripts to connect to machines that do and don't start tmux, or make them all start tmux. Nov 22, 2019 at 12:08

You must log in to answer this question.

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