In tmux, can I get `exit` to exit the containing terminal window and not the session itself?

So when I open a new terminal (I use terminator on Arch Linux), I have it configured to either open a new tmux session if one doesn't exist, or attach to an existing one. When I type exit at the prompt, it quits the tmux session. I have to type exit again to quit the terminal. What I want is that typing exit once will quit the terminal, but leave tmux running, so the next time I open the terminal it will reattach to the previous tmux session. Essentially, this is the equivalent of clicking the exit button for the window manager, but I want this functionality when typing exit.

EDIT:

This is something like what I want:

alias exit='if [[ $TMUX = "" ]]; then exit; else tmux detach; exit; fi'

but the issue is the exit after the tmux detach should get called in the terminal containing the tmux session, not the tmux session itself.


Solution 1:

We have to declare two functions one to start tmux and the other to exit tmux :

function ttmux {
  if (pgrep tmux); then
    tmux attach
  else 
    tmux
  fi
  builtin exit
}

This will execute either (tmux attach or tmux) if tmux process existed or not , after you finish using tmux , built-in exit will be executed to close the terminal(if there isn't nested shell).

function exit {
  if [ ${TMUX} ]; then
      tmux detach
  else 
      builtin exit
  fi
}

If you inside tmux will detach it , if not will execute built-in exit

Put them in your .bashrc or .zshrc and change function name if you wish, and call them.

>> ttmux # to start tmux
>> exit # to detach tmux