I'm working on a script where I use the cat command to create another script that should run after a reboot. The issue I'm encountering is that within the contents I'm passing to the cat command, there's a division operation that's causing a divide by zero error. Here's the relevant line:
result=$((div1 / div2))
The div1 and div2 variables are set earlier in the script, but they shouldn't be evaluated in the cat command. My understanding was that using here-documents with cat would prevent evaluation, especially when using this format:
cat < my_script.sh
# code here that should not execute
EOF
However, if I include the division line, I get an error indicating that there's a division by zero issue on the line with the cat command. It seems like part of the script is being evaluated before it's meant to. I've used cat many times without this problem, and the syntax seems correct according to my editor.
4 Answers
The problem is that by default, the content inside a here-document is treated as if it's in double quotes, meaning variable substitution occurs. To avoid this, you can use single quotes around your EOF like this:
cat < my_script.sh
Doing so will prevent the shell from interpreting the variables in that section.
Also, remember that any quotes around the terminator will prevent interpretation, not just single quotes. So you can use any kind of quotes!
By the way, you don't need to escape underscores in filenames in bash. The shell isn't reading them as special characters. You might also wanna make sure your redirection operator is grouped correctly,
To get the content to treat strictly as text, just quote at least one character of the EOF. You could also write it without any special characters. Just keep in mind that in arithmetic contexts like this, you don't need the dollar sign for variables.
From what you've described, you seem to have misunderstood how here-documents work. If you don't quote your EOF, the shell interprets it as normal input, which means variable expansion happens. Check out the man pages for more details; they'll clarify that quoting at least one character in your terminator is necessary to avoid this issue.
Oh wow, I didn’t realize that. It makes sense now. Thanks for pointing it out!
Just to add, you can also escape the dollar sign:
result=

Yeah, that works! I can’t believe I overlooked that—I spent a good hour on this before figuring it out. Thanks for the quick fix!