How does the exit command work on a Unix terminal?
man bash
exit [n] [...] A trap on EXIT is executed before the shell terminates.
Such traps are often used to clean up tmpfiles on exit, see https://stackoverflow.com/questions/687014/removing-created-temp-files-in-unexpected-bash-exit
Define an exit trap like this (for better testing in a new shell):
$ bash
$ trap "rm filetodelete" EXIT
Show defined EXIT trap:
$ trap -p EXIT
trap -- 'rm filetodelete' EXIT
Test:
$ exit
rm: cannot remove ‘filetodelete’: No such file or directory
Note that exit
may be "called" implicitly too. So instead of exit
you could have also triggered the trap by kill -HUP $$
.
Well usually you would only see execution upon exiting a shell if you've manually configured this. But maybe one of the packages you've installed came with a bash exit shell script...
check;
~/.bash_logout
maybe you'll find a script call from there, it's an odd one...
The exit
command is a special built-in command in shells. It has to be built-in as it needs to exit the shell process.
It exits the shell with the exit status provided if any or that of the last command otherwise.
Upon exiting, the shell will run the EXIT
traps if any. See the output of trap
(in Bourne-like shells) for the currently set ones.
With many shells, if the shell was invoked as a login shell (some systems/users configure terminal emulators to start a login shell), it will also run the code stored in special files like ~/.logout
, ~/.zlogout
, ~/.bash_logout
and possibly corresponding ones in /etc
depending on the shell.
You could do a set -x
before calling exit
to get an idea of where those commands are being run from.