Trouble with running cd with sudo as another user

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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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'

Method 2

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'

Method 3

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x