In Tmux, I frequently start fresh shells and end them when the task I needed them for is finished. Sometimes I intend to close a window but instead close the last remaining shell. This leaves me with a plain terminal emulator.

I would like to use Ctrl-D to close shells fast and easy but prevent to close the last remaining shell as strict as possible. Thus, this closely related question does not fit as it only makes closing all shells a bit inconvenient to prevent unintended quits. I want inconvenience only for the last remaining shell.

Does anyone know how this could be achieved?


There is another question that asks for modified Ctrl+D. My answer there can be adjusted to your case, the result is:

stty eof '^T'
bind '"\C-d": "\C-x\C-t\C-x\C-d"'
bind -x '"\C-x\C-t": _exit_maybe'
_exit_maybe() { [ -n "$READLINE_LINE" ] && return
                [ "$(tmux list-windows | wc -l)" -gt 1 ] && exit
                [ "$(tmux list-panes | wc -l)" -gt 1 ]  && exit   
bind '"\C-x\C-d": delete-char'

Please read the other answer for explanation of the main trick. Here the function is different. Its logic:

  • if the line is not empty, do nothing;
  • otherwise if there is another window, exit the shell;
  • otherwise if there is another pane, exit the shell;
  • otherwise do nothing.

The code will affect a single shell, the one you run it in, nothing more. Pasting it into your ~/.bashrc seems the right thing to do. You will probably want to improve the solution: check if the shell is inside tmux before changing the behavior of Ctrl+D, so shells outside of tmux are unaffected. Like this:

if [ -n "$TMUX" ]; then
   # the above code here

Possible problems:

  • You asked about "last shell". My code prevents exit in Bash in the last pane in the last window. This is not equivalent, although may be enough.

  • Possible race condition. Imagine two panes, two shells. One is about to exit and you hit Ctrl+D in the other one. The function "sees" the pane that is about to exit and lets the other shell exit. The two shells exit semi-simultaneously.

  • Awesome! Thank you very much! Checking for the last pane too is what I actually wanted. I do not consider the race condition to be an actual problem at all. – Max Görner Aug 7 '19 at 6:58

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.