1

How can I disable command substitution in the EOF heredoc?

#!/bin/bash
executableFile="executableFile.sh"
firstFolder="blablabla"
cat <<EOF >$executableFile
    secondFolder="blablabla2"
    if [ \$(cat something) == "blub" ]; then
        echo $firstFolder
        echo $secondFolder
    fi
EOF

The value in the if clause should be requested when executing the executableFile

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    I'm curious why you're creating a script from a script. Dynamic script generation is a [code smell](https://en.wikipedia.org/wiki/Code_smell). Can you explain your underlying goal? We can probably suggest a better way to do it with static scripts. – John Kugelman Jan 26 '21 at 11:53

1 Answers1

3

Quoting 'EOF' will disable all special characters and treat the heredoc literally.

cat <<'EOF' >$executableFile
    secondFolder="blablabla2"
    if [ $(cat something) == "blub" ]; then
        echo $firstFolder
        echo $secondFolder
    fi
EOF

I also recommend double quoting all variable expansions. It's not always necessary, but usually it is and it's just a good habit to get into.

cat <<'EOF' >"$executableFile"
    secondFolder="blablabla2"
    if [ "$(cat something)" == "blub" ]; then
        echo "$firstFolder"
        echo "$secondFolder"
    fi
EOF
John Kugelman
  • 349,597
  • 67
  • 533
  • 578