Output of a command within here-document

Issue

I have a script which contains the code block:

cat << EOF > new_script.sh
...
echo "$(pwd)" >> log.txt
...
EOF

The script new_script.sh is set to run at a later time. Bash recognizes the $(pwd) within the script and evaluates it before it looks at the entire EOF block, so the pwd of the current directory is output instead of the pwd of new_script.sh when it is run. Why is this the case (what logic does bash use to know to evaluate $(command)) and what is the best solution to this?

Solution

By adding an escape $, \$ , you can solve this issue.

cat << EOF > new_script.sh
...
echo "\$(pwd)" >> log.txt
...
EOF

Answered By – mikesdataa

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published