I would like a Tmux command that is similar to choose-session (PREFIX s) but kills the current session if another is selected.

Ideally the command would detach the current session if it was attached elsewhere but kill it if this was the only attachment. This can be discovered with tmux display -p '#{session_many_attached}'

there is a similar question but it's quite old and asks the question in reverse (query, kill, connect).


This binds PREFIX C-s to choose a session, switch to it and then kill the prior session:

bind-key C-s \
  if-shell "(($(tmux display -p '#{session_many_attached}') > 0))" \
    choose-session \
    "run-shell \"tmux choose-session \\\"switch-client -t '%%'; kill-session -t '$(tmux display -p '#S')'\\\"\""

I've used shell expressions (another answer that did not use the shell would be great!). First I use Tmux's if-shell to decide whether there are multiple attached clients. If there are then I just invoke the standard choose-session command.

However, if this is the only client attached to the session, I pass a custom command to choose-session but I do it in shell (with run-shell) so that I can build the command-line passed to choose-session.

That command-line is built of two commands:

  • switch-client -t '%%' which is what choose-session uses by default (see man tmux for an explanation).
  • kill-session -t '$(tmux display -p '#S')' first uses a subshell to get the name of the current session (it hasn't yet been destroyed) and passes that as a parameter to kill-session.

The final command requires lots of escaping to make it work. The if-shell takes three arguments: a shell command and two tmux commands. These need to be quoted if they contain whitespace. Therefore, the third argument run-shell... is quite nasty!

(tmux 2.3)

  • 1
    Very cool answer! I'm using fish as shell and so I had to change $(tmux display ...) by (tmux display ...). – TvE Dec 21 '17 at 5:32
  • Thank you for this great answer! Just for clarification: to make the keybinding work it has to be put into ~/.tmux.conf and then tmux has to be restarted. – FlyingFoX Nov 27 '18 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.