I'm having a problem with bash variable substitution. Here's a silly example of what I am trying to do. I need to output a new script from a bash script. A line (see echo in my example) has a mixture of variables that should not be replaced and variables that should be replaced.

cat << EOF > mynewscript.sh
    read DONTREPLACE < /home/$REPLACE/localinput.txt
    echo $DONTREPLACE > /home/$REPLACE/somefile.log
exit 0

This isn't a real example, but it does illustrate the problem. Let's say that I need to know the absolute path in advance and that I want $REPLACE evaluated in my original script. But I do NOT want $DONTREPLACE evaluated/replaced in my script. $DONTREPLACE should be output exactly like that to the new script.

Therefore, quoting 'EOF' in making the here document doesn't work.

I hope I'm explaining this well enough.

I don't know of another solution. I appreciate any ideas, but I prefer really simple ideas/solutions. It doesn't have to be elegant.


You should use \ to escape the $ in front of DONOTREPLACE. See example and output below

cat <<EOF
> echo $REPLACE

echo 10
  • It doesn't get any simpler than that! haha Thanks! – MountainX Jun 21 '13 at 23:03

I think a better solution, if you're using bash is escape the "EOF" marker. Like this:

cat > mytest << \EOF

cat mytest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.