What is the difference between the commands builtin cd and cd?
The cd
command is a built-in, so normally builtin cd
will do the same thing as cd
. But there is a difference if cd
is redefined as a function or alias, in which case cd
will call the function/alias but builtin cd
will still change the directory (in other words, will keep the built-in accessible even if clobbered by a function.)
For example:
user:~$ cd () { echo "I won't let you change directories"; }
user:~$ cd mysubdir
I won't let you change directories
user:~$ builtin cd mysubdir
user:~/mysubdir$ unset -f cd # undefine function
Or with an alias:
user:~$ alias cd='echo Trying to cd to'
user:~$ cd mysubdir
Trying to cd to mysubdir
user:~$ builtin cd mysubdir
user:~/mysubdir$ unalias cd # undefine alias
Using builtin
is also a good way to define a cd
function that does something and changes directory (since calling cd
from it would just keep calling the function again in an endless recursion.)
For example:
user:~ $ cd () { echo "Changing directory to ${1-home}"; builtin cd "$@"; }
user:~ $ cd mysubdir
Changing directory to mysubdir
user:~/mysubdir $ cd
Changing directory to home
user:~ $ unset -f cd # undefine function
In most instances, there is no difference (but see below). The cd
command is a built-in command in all shells. It needs to be built-in1 as an external command can not change the environment of the invoking shell, and changing the working directory constitutes a change in its environment.
The bash
command builtin
forces the shell to use the built-in version of a command, even though there may be a shell function, alias, or external command available with the same name.
In the case where there is e.g. a shell function with the name cd
, then builtin cd
would not call that. Using builtin cd
bypasses any overloaded functionality that may have been added through a shell function or alias by the user.
Example:
The cd
built-in command may be overloaded by a function that updates the prompt:
cd() {
builtin cd "$@" && PS1=$(__update_prompt)
}
where __update_prompt
is some other user-supplied function that outputs a string.
The builtin cd
in the function would not call the function recursively. Using builtin cd
in a shell where this function is active, would additionally not call the function.
1There are Unices with an external cd
command (macOS, and, I believe, Solaris). The purpose of that command, which can't change the working directory for a shell, is possibly to satisfy the POSIX standard, which lists cd
as one of the external utilities that should be available (cd
is not one of the "special builtin utilities"). It may also serve as a test to see whether changing work directory to a given directory would be possible.