Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash tries to execute commands in heredoc

I am trying to write a simple bash script that will print a multiline output to another file. I am doing it through heredoc format:

#!/bin/sh

echo "Hello!"
cat <<EOF > ~/Desktop/what.txt
a=`echo $1 | awk -F. '{print $NF}'`
b=`echo $2 | tr '[:upper:]' '[:lower:]'`
EOF

I was expecting to see a file in my desktop with these contents:

a=`echo $1 | awk -F. '{print $NF}'`
b=`echo $2 | tr '[:upper:]' '[:lower:]'`

But instead, I am seeing these as the contents of my what.txt file:

a=
b=

Somehow, even though it is part of a heredoc, bash is trying to execute it line by line. How do I prevent this, and print the contents to the file as it is?

like image 979
SexyBeast Avatar asked Dec 20 '15 11:12

SexyBeast


1 Answers

Quote EOF so that bash takes inputs literally:

cat <<'EOF' > what.txt
a=`echo $1 | awk -F. '{print $NF}'`
b=`echo $2 | tr '[:upper:]' '[:lower:]'`
EOF

Also start using $() for command substitution instead of old and problematic ``.

like image 176
heemayl Avatar answered Oct 07 '22 13:10

heemayl