6

Similar to a post about cd, I've overwritten exit to do the following:

function exit() { $HOME/script.sh && builtin exit "$@"; }

Though this works as expected when exit is called directly, when the shell is exited via CTRL-D, this does not execute, OR, if it does execute, the script doesn't manage to finish.

What gives? Is some method other than exit called when CTRL-D is used?

2 Answers 2

11

When you press Ctrl+D, what you really say to bash is EOF (end of file). Thus, the shell just terminates because there's no more input to read. If you want to perform actions on exit, use a trap:

trap "~/script.sh" exit

Using the "exit" trap, you can execute any shell commands just before the shell exits, and it doesn't matter whether the shell was terminated by exit or by Ctrl+D.

7
  • What I really want is to trigger a method when EOF is encountered by the terminal, not execute another method. The snippet I showed above makes it so script.sh executes if I manually execute exit, but I don't want to do this. Feb 12, 2013 at 18:17
  • I don't understand what you want. Can you explain what is, in your opinion, the difference between "trigger a method" and "execute a method"? In your question, you overwrite "exit", thus when you type exit, your script is run, but not when you end the shell with Ctrl+D. What I have written here is a way to execute arbitrary commands whenever the shell exits, be it through typing exit or Ctrl+D. Are you saying that this wasn't your intention? Could you then edit your question as to what you're really looking for? Feb 12, 2013 at 22:17
  • It seems I am unclear on what this does. Where do I place this? I've put it in my .bashrc and the same behavior is observed on EOF. Feb 12, 2013 at 23:45
  • I have modified my answer to include some explanation: trap **<any command>** exit causes this command (any bash command, can be built-in or self-defined function) to be executed whenever the shell exits (no matter if through EOF or exit). The question for me is still: what do you actually want? Would you want to only execute your command on EOF, but not upon typing exit? Feb 13, 2013 at 7:36
  • I want to execute it in either situation. It's a clean up for values that get tracked when .bashrc runs (when shell opens) and when cd is called (I briefly reference cd in my original question). Feb 13, 2013 at 8:28
0

From the bash man page: "When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists."

1
  • 2
    The key word here is "login"; .bash_logout is not executed for non-login shells.
    – chepner
    Feb 12, 2013 at 14:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .