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.

  • 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.
    – Garstlig
    Apr 23 '19 at 23:01

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.


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"'
  • Thanks too many questions on this topic and too many answers but that save my day.
    – Adiii
    Nov 20 '18 at 10:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.