How do I keep quotes when outputting shell variables?… here is a solution to the problem.
How do I keep quotes when outputting shell variables?
The following line:
`eval echo echo $VAR=\\$$VAR` >> $FILE
Output to a file named $FILE
:
FOO=value_of_full
BAR=value_of_bar
I want to output quotes, for example:
FOO="value_of_full"
BAR="value_of_bar"
I’ve tried using \
” and ""
but neither works as I expected.
Solution
It is your eval
that engulfs your offer.
You can use bash >= 2.0 to mitigate eval
The need:
echo "${VAR}=\"${! VAR}\"" >> $FILE
Unfortunately, double (or triple…) is not supported) Dereference, so you cannot execute ${!! VAR}
or ${!${! VAR} }
– You still need to resort to the eval
method for those who have resorted to it. But I don’t think you need that in this case.
If you really want to use eval
, then you will have to double escape your escape, like this:
eval echo "$VAR=\\\"\$$VAR\\\"" >> $FILE
Or, if you really need an extra level of execution (as in the example above), then you need to escape it three times!
`eval echo echo $VAR=\\\\\"\\$$VAR\\\\\"` >> $FILE
Personally, I prefer the first method 🙂