[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: [Help-bash] bash variable interpolation
From: |
Eric Blake |
Subject: |
Re: [Help-bash] bash variable interpolation |
Date: |
Thu, 19 Mar 2015 16:42:29 -0600 |
User-agent: |
Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Thunderbird/31.5.0 |
On 03/19/2015 04:04 PM, Peng Yu wrote:
> Hi,
>
> I want to interpolate variable in a bash string variable. But the
> following code shows the spaces are not maintained.
Insufficient quoting on your part.
> There is some
> built-in features in perl to do string interpolation. Does anyone know
> the best way to do string interpolation in bash? Thanks.
eval does string interpolation. But it is a very heavy hammer, and
should be avoided if there is any other way to do what you really need
done, because it is so easily misused (in particular, use of eval on
unvetted user-supplied is a gaping security hole).
>
> ~$ cat main.sh
> #!/usr/bin/env bash
>
> x=ABC
> y=IJK
> z=XYZ
> str='$x $y $z'
> eval echo "$str"
Remember, eval basically causes a second pass of quote removal. You
executed the command:
"eval" "echo" "$str"
which is the same as:
"eval" "echo" "$x $y $z"
then after quote removal, it gets interpolated as if you had written:
echo $x $y $z
at which point the extra spaces are eaten. You WANT the interpolated
string to have proper quoting, as if you had written:
echo "$x $y $z"
which means your original eval has to add one more layer of quoting
beyond that:
eval echo \""$str"\"
That way, $str is expanded as part of the command line to be eval'd, but
there are still double quotes available for the string that eval is
parsing to preserve the spacing.
And once you understand that, you will see why eval should be avoided if
there is any other way to accomplish what you really need, because it is
far too easy to get quoting wrong when you have to think about multiple
layers of quoting being stripped, not to mention user-controlled input
cause security breaches by executing arbitrary code when you fail to
sanitize the input string.
--
Eric Blake eblake redhat com +1-919-301-3266
Libvirt virtualization library http://libvirt.org
signature.asc
Description: OpenPGP digital signature
- [Help-bash] bash variable interpolation, Peng Yu, 2015/03/19
- Re: [Help-bash] bash variable interpolation, Eduardo A . Bustamante López, 2015/03/19
- Re: [Help-bash] bash variable interpolation, Peng Yu, 2015/03/19
- Re: [Help-bash] bash variable interpolation, Eduardo A . Bustamante López, 2015/03/19
- Re: [Help-bash] bash variable interpolation, Greg Wooledge, 2015/03/20