[mdlug] Evil eval
Carl T. Miller
carl at carltm.com
Thu Oct 2 11:25:26 EDT 2014
Jeff Hanson wrote:
> Thanks. Somebody on Reddit told me the same thing. I've never used them
> before. The quotes worked but I just couldn't understand why the escapes
> didn't for the second variable in the echo line.
It's easier to see what's going on in the first case,
where $varname\_lc is used to add the string in $varname
with the string "_lc". Using the "\" only worked because
the first time it was evaluated it gave a string that
wouldn't be reinterpreted during the next evaluation.
The preferred way to do this is to use ${varname}_lc to
distinguish it from ${varname_lc}.
In the second case the first evaluation gave a string that
would be reinterpretted, hence the (un)expected results.
\$$varname\_lc --> ${varname}_lc --> _lc
c
> On Thu, Oct 2, 2014 at 6:28 AM, Carl T. Miller <carl at carltm.com> wrote:
>
>> Jeff Hanson wrote:
>> > An eval echo statement is not working as I would expect. The first
>> > derived
>> > variable name works with the suffix quoted or escaped. The second
>> only
>> > works quoted. Since it behaves the same in both Bash and Dash I'm
>> > assuming
>> > it's my fault. Example with various combinations in the output:
>> >
>> > #! /bin/sh
>> > test1a_uc="A"
>> > test1b_uc="B"
>> > test1c_uc="C"
>> >
>> > for varname in test1a test1b test1c; do
>> > eval $varname"_lc"=\$\(echo "\$$varname""_uc | tr '[:upper:]'
>> > '[:lower:]'"\)
>> > done
>> >
>> > # Output
>> > echo "Quotes both:"
>> > for varname in test1a test1b test1c; do
>> > eval echo "$varname""_lc: \$$varname""_lc"
>> > done
>> > echo "Escape first, quotes second:"
>> > for varname in test1a test1b test1c; do
>> > eval echo "$varname\_lc: \$$varname""_lc"
>> > done
>> > echo "Quotes first, escapes second:"
>> > for varname in test1a test1b test1c; do
>> > eval echo "$varname""_lc: \$$varname\_lc"
>> > done
>> > echo "Escapes both:"
>> > for varname in test1a test1b test1c; do
>> > eval echo "$varname\_lc: \$$varname\_lc"
>> > done
>>
>> Jeff, try using this line where you want to escape the
>> second derived variable. I think this does what you
>> want it to.
>>
>> eval echo "${varname}_lc: \$${varname}_lc"
>>
>> c
>>
>>
>> _______________________________________________
>> mdlug mailing list
>> mdlug at mdlug.org
>> http://mdlug.org/mailman/listinfo/mdlug
>>
> _______________________________________________
> mdlug mailing list
> mdlug at mdlug.org
> http://mdlug.org/mailman/listinfo/mdlug
>
More information about the mdlug
mailing list