Why does 'sudo pwd' work but not 'sudo cd'?

Many of the StackOverflow answers suggest that it is because cd is a builtin, but type cd and type pwd both return "shell builtin" and only sudo cd returns a "command not found".

So is cd handled as a special case contrary to many answers on SO which is "sudo only works with programs"?

2 Answers

pwd exists as both a shell builtin (which is why type pwd returns that it is a shell builtin) and separately as a GNU Core Utility. The version of pwd that your system is using is the GNU Core Utility version. It is a executable and as such sudo can be used to run it; unlike cd which is a shell builtin command.

You can verify this for yourself.

Type both these commands youself and observe the outcomes. (if there are multiple versions of the same command in your system the which command will tell you which one is being invoked when you enter it)

which pwd
which cd

A shell builtin will return no folder path to an executable when you run the which command. Here are example outputs of both commands on my system:

nate@linux:~> which pwd
/usr/bin/pwd
nate@linux:~> which cd
which: no cd in (/home/nate/bin:/usr/local/bin:/usr/bin:/bin:/usr/bin/X11:/usr/games:/usr/lib/mit/bin:/usr/lib/mit/sbin:/home/nate/Scripts:/home/nate/Scripts)

There is a pwd executable somewhere (try whereis pwd) and sudo uses it.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like