Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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|improve this answer
    
It doesn't get any simpler than that! haha Thanks! –  MountainX Jun 21 '13 at 23:03

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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