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?

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

3 Answers3

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.

Braiam
  • 35,991
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)

Archemar
  • 31,554
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"

jlliagre
  • 61,204
  • 1
    Down voters should think twice ... or at least leave a comment. – jlliagre Oct 16 '14 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. – G-Man Says 'Reinstate Monica' Oct 16 '14 at 15:29
  • 1
    @jlliagre your assertion is wrong. http://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." – phemmer Oct 16 '14 at 16:00
  • 3
    @Patrick My assertion is right. Read closely the last paragraph of http://pubs.opengroup.org/onlinepubs/9699919799/utilities/V3_chap01.html#tag_17_06 – jlliagre Oct 16 '14 at 16:19
  • 1
    @G-Man Thanks for commenting. Answer updated to provide an answer, more explanations and a workaround. – jlliagre Oct 16 '14 at 16:28