3

I have one bash script that is designed to output another bash script. I am using cat. I want to evaluate some of the expressions in output script, but not others.

PROJECT=myproject

cat << EOF > create_dir.sh
#!/usr/bin/env bash

DATE=`date '+%y%m%d-%H%M'`
mkdir $PROJECT/\$DATE
EOF

The resulting create_dir.sh file looks like this:

#!/usr/bin/env bash

DATE=171123-1834

mkdir myproject/$DATE

The result that I want is this:

#!/usr/bin/env bash

DATE=`date '+%y%m%d-%H%M'`

mkdir myproject/$DATE

How can I modify this script so that the expression following DATE= is not evaluated, while at the same time ensuring that $PROJECT is evaluated?

4

You need to escape the '`' symbols since they mean "execute this code". So that line should look like:

DATE=\`date '+%y%m%d-%H%M'\`
  • 1
    I'ld maybe recommend to use $( ... ) instead of the `` ` `` in order to have to escape only one symbol /$ – derHugo Nov 24 '17 at 5:20
4

cat << \EOF

If the label is quoted then the here document is taken as is. Or else quote the backquotes in the here document.

The relevant part of the manual page is:

If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence \<newline> is ignored, and \ must be used to quote the characters \, $, and `.

Note that this solution will copy the here document verbatim; to have some expansions done and others not done the only solution is to use \ to quote those constructions which are not be expanded.

  • 1
    +1; Double quotes around EOF works well too. Example: cat > file.asc << "EOF" – Videonauth Nov 23 '17 at 15:55
  • 1
    As do single quotes. – choroba Nov 23 '17 at 16:05
  • This solution sounds interesting having only parts of EOF evaluated for a similar case I have. Could you please provide a complete example using the OPs snipped? – derHugo Nov 23 '17 at 18:27
  • @derHugo: Exactly as writen by the OP, just replacing EOF with \EOF. The contents of the here document is then copied verbatim. – AlexP Nov 23 '17 at 19:14
  • But he doesn't want that but the $PROJECT shall be evaluated. – derHugo Nov 23 '17 at 21:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.