ssh to server and switch user and change a directory
16,309
Use the -c switch to pass your command to su. A complex command must get enclosed in quotes or double quotes. Since you are already using double quotes, either use single quotes or escape the inner pair of double quotes.
Examples:
ssh -t username@hostname "sudo su - otheruser -c \"cd /path/to/directory && command\""
ssh -t username@hostname "sudo su - otheruser -c 'cd /path/to/directory && command'"
ssh -t username@hostname 'sudo su - otheruser -c "cd /path/to/directory && command"'
Author by
Jeff Schaller
Unix Systems administrator http://www.catb.org/esr/faqs/smart-questions.html http://unix.stackexchange.com/help/how-to-ask http://sscce.org/ http://stackoverflow.com/help/mcve
Updated on September 18, 2022Comments
-
Jeff Schaller over 1 year
I Need to ssh to a server then switch user and change the directory and then run a command. Now am doing
ssh -t username@hostname "sudo su - otheruser && cd /path/to/directory && command"
. But this is not changing the directory it just switched the user and ran the command.-
Garstlig about 5 yearsNo offence, but I don't agree my answer is a duplicate of mentioned answer since OP's problem is not simply how to pass a command to
su
, but also how command concatenation and quoting work.
-
-
Adiii over 5 yearsThanks too many questions on this topic and too many answers but that save my day.
-
Roman Grinyov about 2 yearsAnd how to leave the terminal opened under the changed user?