tags:

views:

1780

answers:

4

I have this multi-line string (quotes included)

abc'asdf"
$(dont-execute-this)
foo"bar"''

How would I assign it to a variable using a heredoc in Bash?

There is still no solution that preserves newlines.

I don't want to escape the characters in the string, that would be annoying...

+1  A: 
VAR=<<END
abc
END

doesn't work because you are redirecting stdin to something that doesn't care about it, namely the assignment

export A=`cat <<END
sdfsdf
sdfsdf
sdfsfds
END
` ; echo $A

works, but there's a back-tic in there that may stop you from using this.

l0st3d
I've updated my question to include $(executable). Also, how do you preserve newlines?
Neil
@l0st3d: So close... Use `$(cat <<'END'` instead. @Neil: The very last newline will not be part of the variable, but the rest will be preserved.
ephemient
+4  A: 

Use $() to assign the output of cat to your variable like this:

VAR=$(cat <<'END_HEREDOC'
abc'asdf"
$(dont-execute-this)
foo"bar"''
END_HEREDOC
)

echo $VAR

Making sure to delimit END_HEREDOC with single-quotes.

Thanks to @ephemient for the answer.

Neil
Actually, this one lets through quotes in some circumstances. I managed to do this in Perl easily...
Neil
A: 
$TEST="ok"
read MYTEXT <<EOT
this bash trick
should preserve
newlines $TEST
long live perl
EOT
echo -e $MYTEXT
This doesn't work at all.
Neil
+6  A: 

You can avoid a useless use of cat and handle mismatched quotes better with this:

read -d '' VAR <<'EOF'
abc'asdf"
$(dont-execute-this)
foo"bar"''
EOF

If you don't quote the variable when you echo it, newlines are lost. Quoting it preserves them:

$ echo "$VAR"
abc'asdf"
$(dont-execute-this)
foo"bar"''
Dennis Williamson