6

I understand that

sudo cd /directory

will return:

sudo: cd: command not found

because cd is a shell builtin and not a binary. But then, why does

sudo echo 'this is a test'

works fine?

What is really going on here? How does sudo find the command echo if it's not a shell?

2
  • 1
    sudo cd /directory works fine here. Check that which cd is in your root user's $PATH. Commented Oct 16, 2014 at 15:01
  • To make matters worse, System IV actually had a /usr/bin/cd which did not change directory in the shell. Commented Oct 16, 2014 at 18:17

3 Answers 3

19

The reason is simple, cd is a shell builtin (and shell function in some shells), while echo is both a binary and a shell builtin:

$ type -a cd  
cd is a shell builtin
$ type -a echo 
echo is a shell builtin
echo is /bin/echo

sudo can't handle shell builtins, but can handle binaries in the $PATH. When you use sudo echo, /bin/echo is found in the $PATH, so it uses that, meanwhile sudo cd can't find cd in the $PATH hence it fails.

4

running

 which echo

gives

 /bin/echo

echo is a plain program, and sudo can "find" it.

On a side note, there must be some option in sudoers(5)

3

The issue is more for sudo cd to fail on your OS than sudo echo to succeed.

sudo cd /directory is quite a legitimate method to check if a given user, likely root here, is allowed to cd to some directory. That is the reason why all Posix compliant OSes do provide an executable version of cd.

So the answer to you question is sudo echo yo works by design because echo is provided by both a shell alias and an executable command but sudo cd /directory does not because your OS, likely Gnu/Linux based, is breaking the Posix standard in this specific case.

A simple workaround for your system would be to run sudo sh -c "cd /directory"

5
  • 1
    Down voters should think twice ... or at least leave a comment. Commented Oct 16, 2014 at 15:24
  • 2
    I didn't vote, but it occurs to me that this doesn't answer the question. You should leave a comment; i.e., the above should be a comment on the question. Commented Oct 16, 2014 at 15:29
  • 1
    @jlliagre your assertion is wrong. pubs.opengroup.org/onlinepubs/009604599/utilities/cd.html "Since cd affects the current shell execution environment, it is always provided as a shell regular built-in." Commented Oct 16, 2014 at 16:00
  • 3
    @Patrick My assertion is right. Read closely the last paragraph of pubs.opengroup.org/onlinepubs/9699919799/utilities/… Commented Oct 16, 2014 at 16:19
  • 1
    @G-Man Thanks for commenting. Answer updated to provide an answer, more explanations and a workaround. Commented Oct 16, 2014 at 16:28