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

tmux

When I exit the last terminal in a tmux session it will automatically close tmux and return me to the parent terminal. Is it possible to instead have tmux switch to another, already running, session instead of closing?

I create a new named session for every task that I work on, such as TRxxx, email, scratch etc and when I am done with one of them I close all the terminals by running exit in every one. When you run exit in the last terminal of a session tmux will return you to the parent terminal but is it possible to get it to just switch to one of the other open sessions instead so I don't have to reattach?

This question is similar to "Kill a tmux session and select another tmux session" but I want to close my terminals the nice way by using exit rather than killing the window.

Best Answer

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.

Related Question