SSH automatically opens a shell on the host. It is easy to run a simple command and get the output and its return value. But what if your command contains variables from the local environment, that need to be quoted? Things get messy real fast: the quotes get misinterpreted1, a subsequent command is run on the local machine instead of the server etc.
There are other solutions, but I find this method the most elegant:
thisvar=something
ssh "$host" << EOF
do_something "$thisvar" && do_something "$anothervar"
do_something_else "$thisvar"
EOF
You can catch the return value:
ssh "$host" << EOF && echo "Success!"
do_something "$thisvar"
EOF
Or the output:
ssh "$host" << EOF > /tmp/result
do_something_else "$thisvar"
EOF
This will become tricky for variables and strings that contain “weird” characters.
For example, my music collection contains many such file and directory names.
In such cases it is better to save those to a file, copy it over, then deal with it there.
or to be more precise: it is easy to get them wrong, maybe even impossible to get right ↩