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.
More on Arguments, I/O, here-docs, process substitution and subshells
How does `getopts` work? Show a complete example.IntermediateWhat is the difference between `getopts` and `getopt`?AdvancedExplain file descriptors 0, 1 and 2 and the main redirection operators.BeginnerWhy is `cmd 2>&1 > file` different from `cmd > file 2>&1`?AdvancedWhat is a here-document, and what is the difference between `<<EOF`, `<<'EOF'` and `<<-EOF`?BeginnerWhat is a here-string (`<<<`)?Intermediate