Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write SSH command over multiple lines

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!

like image 826
dspshyama Avatar asked Aug 18 '15 21:08

dspshyama


2 Answers

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
"
like image 117
Alfe Avatar answered Oct 03 '22 13:10

Alfe


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.

like image 36
ntki Avatar answered Oct 03 '22 12:10

ntki