Skip to content
Advertisement

Create a heredoc that doesn’t interpret anything

I’m writing a script for a friend who is not experienced with bash. The script generates a backup script, generates a crontab and runs crontab to create a cron job.

I want to date these backups, so currently the script (what’s relevant) is:

cat <<EOF > ~/scheduledBackups/scripts/finalCutScript.bash
mkdir -p ~/scheduledBackups/FinalCut-`date +%a-%b-%d-%Y_%H`
cp -r $BACKUP_DIR/* ~/scheduledBackups/FinalCut-`date +%a-%b-%d-%Y_%H`
EOF

This, however, generates finalCutScript.bash with the date as is when the “installer” script is run.

Is there a way to place exactly that heredoc within finalCutScript.bash? I want to keep everything in one script so that I can use this script framework later.

Elaboration

Expected behaviour:

I want the file that the heredoc is piped into to contain

mkdir -p ~/scheduledBackups/FinalCut-`date +%a-%b-%d-%Y_%H`
cp -r $BACKUP_DIR/* ~/scheduledBackups/FinalCut-`date +%a-%b-%d-%Y_%H`

Actual behaviour

The file generated by that heredoc contains

mkdir -p ~/scheduledBackups/FinalCut-Fri-Aug-05-2016_16
cp -r ~/Documents//* ~/scheduledBackups/FinalCut-Fri-Aug-05-2016_16

Advertisement

Answer

You should EOF in heredoc and use $(...) for command substitution:

cat <<-'EOF' >~/scheduledBackups/scripts/finalCutScript.bash
mkdir -p ~/scheduledBackups/FinalCut-$(date +%a-%b-%d-%Y_%H)
cp -r $BACKUP_DIR/* ~/scheduledBackups/FinalCut-$(date +%a-%b-%d-%Y_%H)
EOF

Update: As per OP’s comment below you can also escape $ for not expanding a variable in current shell:

BACKUP_DIR='foobar' # variable to be used below in here-doc

cat <<-EOF >~/scheduledBackups/scripts/finalCutScript.bash
mkdir -p ~/scheduledBackups/FinalCut-$(date +%a-%b-%d-%Y_%H)
cp -r $BACKUP_DIR/* ~/scheduledBackups/FinalCut-$(date +%a-%b-%d-%Y_%H)
EOF

Above command will use $BACKUP_DIR from your current environment but will add literal $(date +%a-%b-%d-%Y_%H) in the output.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement