I have a command,

# ssh -t computer.A 'command'

to execute a simple command on computer.A remotely over SSH.

To add to this, I want to execute a command on computer.B through computer.A.  In my head it would look like this:

# ssh -t computer.A 'ssh -t computer.B 'shutdown -p now' shutdown -p now'

This command would first shutdown computer.B and then computer.A, but it only shuts down computer.B, and ignores the command to shutdown computer.A.

What is going wrong?


You would need to escape your quotes and separate the two commands from each other.

ssh -t computer.A 'ssh -t computer.B \\'shutdown -p now\\'; shutdown -p now'

If you wanted the second shutdown on computer.A only to run if the first was successful, replace the ; with &&.

You could also alternate the quotes like so:

ssh -t computer.A 'ssh -t computer.B "shutdown -p now"; shutdown -p now'
  • Shouldn't the first command be: ssh -t computer.A 'ssh -t computer.B '\''shutdown -p now'\''; shutdown -p now' – Isaac Feb 7 '18 at 22:42
  • That will also work. – virullius Feb 9 '18 at 14:52

Imagine being on computer A. You want to shutdown computer B. How do you do this?

You type,

ssh -t computer.B 'shutdown -p now'

Now you want to execute that command ("ssh -t computer.B...") on your computer. You need to quote it, but in the command there are already two quotes, so you need to escape them:

ssh -t computer.A 'ssh -t computer.B \'shutdown -p now\''

and actually you want to execute two commands, so you need to add it inside the outer quotes:

ssh -t computer.A 'ssh -t computer.B \'shutdown -p now\'; shutdown -p now'

If you want to iterate this by connecting to your computer from outside, just rinse and repeat:

  • first stage, escape all quotes and all slashes, so \ becomes \\ and ' becomes \'. Which means that \' becomes \\\':

    ssh -t computer.A \'ssh -t computer.B \\\'shutdown -p now\\\'; shutdown -p now\'
  • second stage: enclose in quotes, add the shutdown command and prepend the ssh instruction:

    ssh -t mycomputer 'ssh -t computer.A \'ssh -t computer.B \\\'shutdown -p now\\\'; shutdown -p now\'; shutdown -p now'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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