0

This question already has an answer here:

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.

marked as duplicate by Jeff Schaller, Hunter.S.Thompson, Timothy Martin, roaima, G-Man Feb 1 '18 at 2:35

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 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 at 23:01
4

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"'
  • 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.