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

6,599

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
Share:
6,599

Related videos on Youtube

Jarek
Author by

Jarek

You may be interested in the story of SE moderator Monica Cellio and how she was unfairly treated by the corporate management of this site. More info here. An update is available. Let's hope we can cultivate a more fair environment for content creators and moderators going forward.

Updated on September 18, 2022

Comments

  • Jarek
    Jarek over 1 year

    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.

  • Jarek
    Jarek almost 11 years
    It doesn't get any simpler than that! haha Thanks!