Interview Prep/Shell Scripting/Arguments, I/O, here-docs, process substitution and subshells

How do you send a here-doc to a remote server over SSH, and when should variables expand locally vs remotely?

AdvancedConceptArguments, I/O, here-docs, process substitution and subshells
Answer
release=v42
ssh -o BatchMode=yes deploy@web1 bash -s -- "$release" <<'REMOTE'
set -euo pipefail
release=$1                               # passed as an argument, expands remotely
cd /srv/app && ln -sfn "releases/$release" current
sudo systemctl reload app
echo "now on $(readlink current) at $(hostname)"
REMOTE

With <<'REMOTE' everything expands on the remote host, and local values are passed as arguments to bash -s --. With an unquoted delimiter, everything expands locally first, which is easy to get wrong ($(hostname) would be the local host). Passing arguments also avoids quoting a value into the script text, which is an injection risk.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arguments, I/O, here-docs, process substitution and subshells