Write SSH command over multiple lines

dspshyama picture dspshyama · Aug 18, 2015 · Viewed 12.7k times · Source

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!

Answer

ntki picture ntki · Aug 18, 2015

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.