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"'
Share:
16,309
Jeff Schaller
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, 2022

Comments

  • Jeff Schaller
    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
      Garstlig about 5 years
      No 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
    Adiii over 5 years
    Thanks too many questions on this topic and too many answers but that save my day.
  • Roman Grinyov
    Roman Grinyov about 2 years
    And how to leave the terminal opened under the changed user?