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?
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'
cd. OP probably wants sudo -i.
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'
I tend to use:sudo su - USERNAME and then do what you need as that user. To quit just type exit
USERNAME and then executing command is different that directly running command as USERNAME