Automatically kill tmux session on session end?

2

I have the following snippet in my .bashrc which starts tmux whenever I'm at the command line:

# Start inside tmux
if [[ $(command -v tmux) ]] && [[ -z $TMUX ]] && [[ $TERM != "screen" ]]; then
     exec tmux
fi

I often access this machine over ssh, and sometimes the pipe breaks for one reason or another (for example closing my laptop). When that happens, the tmux session continues to exist in detached state.

How can I automatically destroy such sessions?

Carl Patenaude Poulin

Posted 2015-12-26T16:16:23.967

Reputation: 185

Why not just start a session on first login and then just reattach to the tmux session if you disconnect and login again? tmux a – ecube – 2015-12-26T16:54:36.217

How would you do this programmatically? The output of tmux list-sessions seems impractical for use with a script. – Carl Patenaude Poulin – 2015-12-27T03:58:41.380

In my .bashrc I have if [ -z "$TMUX" ]; then tmux a || tmux; fi. – Kamil Maciorowski – 2019-10-17T12:31:08.187

Answers

3

Use the destroy-unattached tmux option:

destroy-unattached [on | off]

If enabled and the session is no longer attached to any clients, 
it is destroyed.

user1686

Posted 2015-12-26T16:16:23.967

Reputation: 283 655