Search code examples
linuxbashcatheredoc

Output of a command within here-document


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