When exiting the last terminal in a tmux session can it switch to another?

I added this to my ~/.tmux.conf:

set-option -g detach-on-destroy off

When I destroy the last shell in a session, it switches to another active session. Once all sessions are closed, tmux exits.


Add these lines to your .bashrc and try:

if which tmux 2>&1 >/dev/null 
then
    # start a new session if not exist
    test -z ${TMUX} && tmux

    # when quitting tmux, try to attach to other session
    while test -z ${TMUX}; do
        tmux attach || break
    done
fi

The closest I got was a tmux function I wrote. I normally exit the shell by hitting Ctrl+D, so I programmed tmux to exit and switch sessions when hitting [PREFIX] Ctrl+D. Put the following in your .tmux.conf:

bind C-d run-shell "                                        \
    if [ #{session_windows} -eq 1 ] &&                      \
       [ #{window_panes}    -eq 1 ] &&                      \
       [ #{pane_current_command}  = 'bash' ]; then          \
        if [ \$(tmux list-sessions | wc -l) -ge 2 ]; then   \
            tmux switch-client -ln;                         \
        fi; tmux kill-session -t \"#S\";                    \
    else                                                    \
        tmux display-message \"Ignoring kill session...\";  \
    fi;                                                     \
    "

Hit [PREFIX] Ctrl+D and it exits the current session if (and only if) it holds only one shell which is not running any other commands. It will switch to another session if possible. I use the bash shell, so you might need to change it to something you are using.

ps: in case it matters, I'm currently using tmux 1.9a.

Tags:

Tmux