41

I use tmux on my server and recently I found to my cost that ctrl-d will exit tmux and lose all the session information, my intention was to simply end the ssh session but failed to notice I was still in tmux until too late.

I am aware that I should be careful in future when using ctrl-d but I wondered if there a way to prevent tmux for exiting when hitting ctrl-d by accident? A solution such as a prompt, confirmation or detaching would be fine.

3 Answers 3

48

To be precise, Ctrld does not exit tmux, but rather a shell. If that shell is running in the only pane of the last window in the tmux session, the session ends and the tmux client exits.

To prevent Ctrld from exiting the shell, you can set the IGNOREEOF shell variable, or set the ignoreeof shell option. Put one of the following in your .bashrc file:

IGNOREEOF=10   # Shell only exists after the 10th consecutive Ctrl-d

set -o ignoreeof  # Same as setting IGNOREEOF=10
2
  • 9
    That is excellent, thanks. I only needed it for tmux so I used set-environment -g 'IGNOREEOF' 2 in .tmux.conf and now I need to hit Ctrl-d 3 times to exit and I am also warned each time with the message: Use "logout" to leave the shell.
    – Cas
    Sep 26, 2012 at 10:43
  • 10
    Setting IGNOREEOF environment variable have no effect in zsh, but "set -o ignoreeof" or "setopt ignoreeof" does.
    – sgtpep
    Apr 24, 2013 at 6:19
17

IGNOREEOF didn't work for me so I just bound Ctrl+D to detach in .tmux.conf:

bind-key -n C-d detach

The -n means no prior escape sequence needed, like the tmux prefix.

6
  • A year and a half later, IGNOREOF didn't work for me before since I'm using zsh. setopt ignoreeof in .zshrc works. But I had to kill all tmux sessions for tmux to source .zshrc. Maybe I could have sourced .zshrc from within tmux...
    – Rohmer
    Aug 21, 2017 at 22:51
  • 1
    I have been using this, but it has an annoying limitation: it detaches on any Ctrl+D, whether it's being sent to the shell or to something like cat > some_new_file.txt. Mar 25, 2018 at 2:42
  • This, however, has a side effect in tmux with more panes open as it doesn’t let you close a pane with ^D.
    – Mr. Tao
    Apr 2, 2018 at 10:01
  • 3
    @Rohmer, prezto taught me to use exec zsh to restart zsh within tmux when I'm playing with the .zshrc
    – krry
    Feb 19, 2019 at 20:58
  • 1
    Your solution is very smooth, just replaced the exit to complete session detach, love it! Thanks! Feb 27, 2019 at 23:44
8

Besides chepner's answer you can stop the terminal from sending EOF entirely by setting eof to undef with stty:

stty eof undef

Reset with:

stty eof '^d'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.