Brydon Gibson Brydon Gibson - 1 year ago 46
Linux Question

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`

This, however, generates
with the date as is when the "installer" script is run.

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


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

Answer Source

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)

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)

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