Notes

Here Documents in Bash

using here documents in bash to feed multiple commands to ssh, with an example that dumps remote databases and restores them locally.

Edit on GitHub

Bash Scripting
2 minutes

tl;dr

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

1ssh otherhost << EOF
2  ls some_folder; 
3  ./someaction.sh 'some params'
4  pwd
5  ./some_other_action 'other params'
6EOF
  • 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

1# the limit string here is: SSHCOMMANDS
2# The variables inside the here doc are quoted
3ssh -i ${REMOTE_SSH_KEY} -p ${REMOTE_SSH_PORT} ${REMOTE_SSH_USER}@${REMOTE_SSH_HOST} /bin/bash << SSHCOMMANDS
4  mysqldump --user="${REMOTE_DB_USER}" --password="${REMOTE_DB_PASS}" --add-drop-database --all-databases | gzip -9 > "${DB_DUMP_FILENAME}".sql.gz
5  gunzip < "${DB_DUMP_FILENAME}".sql.gz | mysql --user="${DB_USER}" --password="${DB_PASS}" --host="${DB_HOST}"
6SSHCOMMANDS

Related

Browse all topics