help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Help-bash] bash variable interpolation


From: Peng Yu
Subject: Re: [Help-bash] bash variable interpolation
Date: Thu, 19 Mar 2015 18:37:30 -0500

On Thu, Mar 19, 2015 at 5:42 PM, Eric Blake <address@hidden> wrote:
> 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"\"

The following example shows that above code is not robust with
respective to arbitrary 'str'.

#!/usr/bin/env bash

x="'"
y=IJK
z=XYZ
str='"$x"  $y  $z'
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.

The real problem is that I want to replace some bash variables in a
file and then print the output.

sed has the problem of not robust with respect to special characters.
Please let me know if there is a convenient solution in bash.

~$ cat main_from_file.sh
#!/usr/bin/env bash

x="'"
y=IJK
z=XYZ
str=$(cat myfile.txt)
eval echo "$str"
~$ cat myfile.txt
"$x" $y $z

-- 
Regards,
Peng



reply via email to

[Prev in Thread] Current Thread [Next in Thread]