13

I want to run a command on a shell on behalf of another user. The command is as follows:

sudo -u USER cd /home/USER

I get

sudo: cd: command not found

What is the correct syntax for the command to pass to sudo?

3 Answers 3

14

cd is a shell builtin. You need to invoke shell for executing shell builtins:

sudo -u USER sh -c 'cd /home/USER'

OR

sudo -u USER bash -c 'cd /home/USER'
1
  • 2
    This won't really do anything useful---the shell will exit right after the cd. OP probably wants sudo -i. Commented Oct 1, 2013 at 0:52
6

cd is not an external command, it is only a shell builtin, so sudo cannot execute it. The reason why cd only exists as a shell builtin is that a process cannot affect the current directory of another process; therefore a program that changes the current directory and exits immediately is useless. (Almost useless: a cd program would return a status that indicates whether it was successful.)

If you want to change to a directory and then run commands as another user, run a shell that does all that.

sudo -u SOMEUSER sh -c 'cd /path/to/directory && dosomething'
1

I tend to use:sudo su - USERNAME and then do what you need as that user. To quit just type exit

1
  • 3
    logging as USERNAME and then executing command is different that directly running command as USERNAME Commented Jun 17, 2015 at 9:02

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.