Here Documents in Bash


a here document is special-purpose code block that you can use to feed commands

ssh otherhost << EOF
  ls some_folder; 
  ./ 'some params'
  ./some_other_action 'other params'
  • a limit string (usually EOF) indicates the start and finish of a here document. It doesn’t have to called EOF, you can call it whatever, e.g. JumanjiXYZ is a valid limit string
  • Variables inside a Here document need to be quoted or else they won’t be substituted, like so: "${VAR}"
  • The ending limit string needs to be at the beginning of the line

Here is an example where a here doc has been used to run multiple commands to the remote server. The script logs in to a remote server, takes a back up of all it’s databases and restores those databases directly on your current server, i.e. the server you ran the commands from

# the limit string here is: SSHCOMMANDS
# The variables inside the here doc are quoted
  mysqldump --user="${REMOTE_DB_USER}" --password="${REMOTE_DB_PASS}" --add-drop-database --all-databases | gzip -9 > "${DB_DUMP_FILENAME}".sql.gz
  gunzip < "${DB_DUMP_FILENAME}".sql.gz | mysql --user="${DB_USER}" --password="${DB_PASS}" --host="${DB_HOST}"