3

I have several sessions in tmux

enter image description here

How to close/kill some of them, without exiting tmux?

If I type exit I am not only closing session, but also exiting tmux, which is not applicable.

2
  • <ctrl>+b d detaches the current tmux session without exiting it
    – Peleion
    May 13, 2020 at 14:02
  • I need to exit it
    – Dims
    May 14, 2020 at 13:00

2 Answers 2

7

Apparently there's a setting for this.

In your ~/tmux.conf:

set-option -g detach-on-destroy off

Now tmux will not detach (close) when the session is destroyed, instead it will go to any other active session.

OLD ANSWER:

I needed exactly this, as my workflow includes short-lived tmux sessions to jump between code projects that are killed at the end.

Since I couldn't find anything I wrote a script that switches to the first other active session before killing the current one and I bound it to Leader X for quick access.

~/.scripts/tmux-kill-session.sh:

#!/usr/bin/env bash

tmux_running=$(pgrep tmux)

if [[ -z $TMUX ]] && [[ -z $tmux_running ]]; then
    exit 0
fi

session_to_kill="$(tmux list-sessions | sed -n '/(attached)/s/:.*//p')"
session_to_switch="$(tmux list-sessions | sed -n '/(attached)/!s/:.*//p' | head -n 1)"

if [[ ! -z $session_to_switch ]]; then
    tmux switch-client -t $session_to_switch 
fi

tmux kill-session -t $session_to_kill

~/.tmux.conf:

bind X run-shell "~/.scripts/tmux-kill-session.sh"
1

You can kill sessions directly within tmux. Let's say you have two sessions: session1 and session2. And you're currently in session1.

Use this, while still in session1, to kill session2.

tmux kill-session -t session2

You should remain within session1. And if you should no longer see session2 in your session list.

3
  • How to kill the same session where I am typing this?
    – Dims
    May 14, 2020 at 13:01
  • Ah. I see. You want to exit the current session and allow tmux to shift you over to a different, active session. Apologies I'm not sure how to do that.
    – iangetz
    May 14, 2020 at 16:55
  • 1
    Helpful to me. Switch to a different session first if necessary, then <prefix>:kill-session -t other-session
    – tremby
    Nov 17, 2023 at 18:48

You must log in to answer this question.

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