28

I'm trying to remote login to a shell and execute a bunch of commands on the shell. But to make it more readable, I'd like to place my code over multiple lines. How should I be doing this?

ssh -o <Option> -x -l <user> <host> " $long_command1; $long_command2; ....  "

Thanks!

dspshyama
  • 403
  • 1
  • 4
  • 10

3 Answers3

41

ssh is in fact just passing a string to the remote host. There this string is given to a shell which is supposed to interpret it (the user's login shell, which is typically something like bash). So whatever you want to execute needs to be interpretable by that remote login shell, that's the whole rule you have to stick to.

You can indeed just use newlines within the command string:

ssh alfe@sweethome "
  ls /home/alfe/whatever
  ping foreignhost
  date
  rm foobar
"
Alfe
  • 56,346
  • 20
  • 107
  • 159
  • You might want to have a look at [this answer](http://stackoverflow.com/questions/32019076/having-an-issue-passing-variables-to-subshell/32019393#32019393) I gave just recently about passing variables into ssh-remote shells. – Alfe Aug 18 '15 at 21:32
28

You can use the Here Documents feature of bash. It is like:

ssh <remote-host> bash <<EOF
echo first command
echo second command
EOF

EOF marks the end of the input.

For further info: use man bash and search for Here Documents.

Edit: The only caveat is that using variables can be tricky, you have to escape the $ to protect them to be evaluated on the remote host rather then the local shell. Like \$HOSTNAME. Otherwise works with everything that is run from bash and uses stdin.

ntki
  • 2,149
  • 1
  • 16
  • 19
2

You can do like in the following example.

ssh -o <Option> -x -l <user> <host> '
pwd
whoami
ls
echo "$PATH"
'
crafter
  • 6,246
  • 1
  • 34
  • 46