Bash – the difference between the commands builtin cd and cd

bashcd-commandshell

I encountered a Linux command, builtin cd.

What is the difference between the commands builtin cd and cd?

In fact, I made some researches about the difference, but I could not find a remarkable and significant explanation about this.

Best Answer

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
Related Question