sudo cd fails (or shell builtins)

terminalOne of the directories within my home directory belonged to root and I was unable to check the contents within. Finally I issued:

$ sudo cd Downloads/
sudo: cd: command not found

I know very well that cd exists and works! What happened???

The reason is cd is not a binary executable but a bash function (aka builtin) and sudo doesn’t work with builtins. So I had to elevate to root first:

$ su
$ sudo -i

and then cd into the directory.

How do you figure out if a command is a builtin? Use type:

$ type cd
cd is a shell builtin
$ type ls
ls is aliased to `ls --color=auto'
$ type touch
touch is /usr/bin/touch

Shell builtins are usually faster than binaries and hence better suited for writing shell scripts.

To list all the bash builtins, run:

$ compgen -b

Leave a Reply

Your email address will not be published. Required fields are marked *