Bash – How to configure bashrc to close all tmux sessions when I close the terminal

bashrctmux

I'm using Gnome Terminal and tmux and I'd like that all tmux sessions were closed when I close the Gnome Terminal, is that possible? I checked the Arch Wiki article on tmux and found some relevant code, but none of them did what I want. Right now, if I close and open the Gnome Terminal I get the the session I had, exactly how it was right before I closed the terminal with all panes and programs running. What I want is that all sessions are killed when I close Gnome Terminal.

Best Answer

Option 1: use .bash_logout

In your .bash_logout file you can add tmux kill-server. This won't work if you aren't in a login shell, or if the shell is killed with SIGHUP.

Option 2: Use bash traps.

This option is probably more robust. Put the following code in your .bash_profile (assuming you use bash).

function close_tmux
{
    tmux kill-server
}
trap close_tmux EXIT

Links to Additional Resources On Traps

Some background on trap statements

A blog post with plenty of trap examples

A chapter on traps from a Bash scripting guide

A Unix & Linux Stack exchange question about traps

Related Question