Commenting out "expr" creates weird behavior

This really puzzles me. The following code gives me the error 'expr: syntax error' when I try to do multi-line comment using here document

<<EOF
echo "Sum is: `expr $1 + $2`"
EOF

Even if I explicitly comment out the line containing the expr using "#", the error message would still exist

<<EOF
#echo "Sum is: `expr $1 + $2`"
EOF

And I observed that this happens only when I supply the 2nd operand to the expr as variable. If I hardcode it to a numeric value then the error message would disappear, that is

<<EOF
echo "Sum is: `expr $1 + 2`"   # expr's second argument numeric value is hard coded, no error now
EOF

Could anyone enlighten me on this?

If you want to disable substitution in a heredoc then you need to quote the tag string:

<<'EOF'
echo "Sum is: `expr $1 + $2`"
EOF
1 Like

A heredoc isn't a shell script. Since there are no comments within a heredoc, # is not a special character.

Regards,
Alister

1 Like

A here document is something that is just read (and expanded) and presented to stdin, and not executed per se. So the echo won't do anything. In the expansion phase, command substitution takes place, and expr will be executed. Are your positional parameters set? I guess not. Try set -- 3 5 and run again - does it succeed?

1 Like