Bash – using bash script to output new script: need mixture of variables to be replaced and not replaced

bashechohere-documentvariable substitution

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.

#!/bin/bash
REPLACE=`whoami`
cat << EOF > mynewscript.sh
    read DONTREPLACE < /home/$REPLACE/localinput.txt
    echo $DONTREPLACE > /home/$REPLACE/somefile.log
EOF
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.

Best Answer

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

REPLACE=10
DONOTREPLACE=20
cat <<EOF
> echo $REPLACE
> echo \$DONOTREPLACE
> EOF

echo 10
echo $DONOTREPLACE
Related Question