When attempting to attach to a new tmux from within a tmux session an error is shown:

sessions should be nested with care, unset $TMUX to force

Why sessions shouldn't be nested is understandable but it makes jumping between tmux sessions annoying as you need to detach manually then re-attach to a new session.

Is it possible to create a command which detaches from the current tmux session and attaches onto the given one without resorting to unsetting $TMUX?

I tried alias tm="tmux detach; tmux new -A -s" however this doesn't work which isn't surprising as tmux new -A -s is run the shell I just detached from not the shell I am returning to.


1 Answer 1

detach-client [-aP] [-E shell-command] [-s target-session] [-t target-client]

[…] With -E, run shell-command to replace the client.


tm() { tmux detach -E "tmux new -A -s '$1'"; }

You may want to add some logic to cover the case where $1 is empty.

  • Don't do this, use switch-client. Commented Jan 2, 2020 at 9:06
  • @NicholasMarriott What is wrong with this approach? The OP used tmux new -A so I assumed the target session may or may not exist. With switch-client you need additional logic in case the target session doesn't exist. Commented Jan 2, 2020 at 9:14
  • It's fine, but switch-client will do less work because the client won't restart. If you want to create the session if it doesn't exist you can do: tmux new -dsfoo; tmux switchc -tfoo. I should really make it so that new-session inside tmux acts like switch-client since that is most likely what the user intends. Commented Jan 2, 2020 at 9:22
  • @NicholasMarriott Seems right. I will upvote such answer if it appears. Commented Jan 2, 2020 at 9:37

You must log in to answer this question.

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