4

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

1 Answer 1

5

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)

2
  • 1
    Very cool answer! I'm using fish as shell and so I had to change $(tmux display ...) by (tmux display ...). Commented Dec 21, 2017 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. Commented Nov 27, 2018 at 12:52

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.