Suppose I want a bash command to do something extra. As a simple example, imagine I just want it to echo "123" before running.
One simply way to do this would be to alias the command. Since we still need the original, we can just refer to it by its exact path, which we can find using which
. For example:
$ which rm
/bin/rm
$ echo "alias rm='echo 123 && /bin/rm'" >> .bashrc
This was easy because I was able to look up the path to rm
using which
.
However, I am trying to do this with exit
, and which
doesn't seem to know anything about it.
$ which exit
$ echo $?
1
The command did not output a path, and in fact it returned a non-zero exit code, which which
does when a command is not in $PATH
.
I thought maybe it's a function, but apparently that's not the case either:
$ typeset -F | grep exit
$ echo $?
1
So the exit
command is not defined anywhere as a function or as a command in $PATH
, and yet, when I type exit
, it closes the terminal. So it clearly is defined somewhere but I can't figure out where.
Where is it defined, and how can I call to it explicitly?
Best Answer
exit
is a shell special built-in command. It was built with the shell interpreter, the shell knows about it and can execute it directly without searching anywhere.On most shells, you can use:
You have to read source of the shell to see how its builtin implemented, here is link to source of
bash
exit builtin.With
bash
,zsh
,ksh93
,mksh
,pdksh
, to invoke theexit
built-in explicitly, usebuiltin
builtin command:See How to invoke a shell built-in explicitly? for more details.