Search code examples
bashterminaltmux

How to exit tmux without leaving my terminal


I'm using tmux on bash, and letting it start automatically from .bashrc. Sometimes I want it disabled, and I should edit my .bashrc to do so. Editting a file everytime I disable tmux is quite troublesome, and I think the easiest way to do the same thing is exiting tmux without leaving terminal. Can I do that?

When I type exit, bash and terminal close. I tried exec bash , but it just restarted bash inside tmux.

I start tmux from code below, according to https://wiki.archlinux.org/index.php/tmux#Bash.

if [[ $DISPLAY ]]; then
        # If not running interactively, do not do anything
        [[ $- != *i* ]] && return
        [[ -z "$TMUX" ]] && exec tmux
fi

If I just run tmux in code above instead of exec tmux, I can achieve my goal. But I don't like that, because I don't understand why the code uses exec tmux rather than tmux and don't wanna change it rashly, and when I run tmux I shoud type exit or C-d twice in order to exit terminal.


Solution

  • (Note: this question should really be on unix.stackexchange.com). One simple solution is to replace the line

    [[ -z "$TMUX" ]] && exec tmux
    

    with

    [[ -z "$TMUX" ]] && { tmux; [ ! -f ~/dontdie ] && exit || rm ~/dontdie; }
    

    This runs tmux as before, but when it exits goes on to test for the existence of a file, ~/dontdie. If the file does not exist the && exit is done and the terminal closes as before. If, however, you create the file before leaving tmux, then you will do the || rm ... part, which removes the file, and continues through the rest of the .bashrc file, leaving you in the bash shell.

    So, to stay in the terminal, from the tmux window you type the commands:

    touch ~/dontdie; exit
    

    instead of just exit, and you will exit tmux and continue in bash. To make it easier you can add a binding in ~/.tmux.conf to a key, such as X:

    bind-key X send-keys 'touch ~/dontdie; exit' Enter
    

    Then you simply type your prefix character, Control-B by default, then X to create the file and exit tmux.