在bash间接变量赋值 [英] Indirect variable assignment in bash
问题描述
似乎在bash中做间接变量设置推荐的方法是使用评估
:
VAR = X; VAL = foo的
EVAL是$ var = $ VAL
回声$ X# - >富
问题就是平常的那个与<$ C $ C>评估:
VAR = X; VAL = $ 1\\ n'pwd
EVAL是$ var = $#VAL坏输出这里
(而且由于它在很多地方推荐的,我不知道,因为这有多少脚本是脆弱的......)
在任何情况下,使用明显的溶液(逃跑)的报价并没有真正的工作:
VAR = X; VAL = 1 \\$'\\ n'pwd \\
EVAL是$ var = \\$ VAL \\#失败,上述
的事情是,bash有可变间接引用出炉,但我没有看到任何这样的方式做间接分配(以 $
{富!}) - - 是否有任何理智的方式来做到这一点。
有关记录,我没有找到一个解决办法,但这不是东西,我会考虑理智......
评估是$ var ='$ {// VAL \\'/ \\'\\\\'\\\\'}'
主要的一点是,推荐的方式来做到这一点是:
评估是$ var = \\ $ VAL
在RHS间接完成了。由于评估
在相同的环境中使用,将有 $ VAL
的约束,因此推迟它的工作原理,既然现在它只是一个变量(与已知的名字),没有任何问题与引用。
Seems that the recommended way of doing indirect variable setting in bash is to use eval
:
var=x; val=foo
eval $var=$val
echo $x # --> foo
The problem is the usual one with eval
:
var=x; val=1$'\n'pwd
eval $var=$val # bad output here
(and since it is recommended in many places, I wonder just how many scripts are vulnerable because of this...)
In any case, the obvious solution of using (escaped) quotes doesn't really work:
var=x; val=1\"$'\n'pwd\"
eval $var=\"$val\" # fail with the above
The thing is that bash has indirect variable reference baked in (with ${!foo}
), but I don't see any such way to do indirect assignment -- is there any sane way to do this?
For the record, I did find a solution, but this is not something that I'd consider "sane"...:
eval "$var='"${val//\'/\'\"\'\"\'}"'"
The main point is that the recommended way to do this is:
eval "$var=\$val"
with the RHS done indirectly too. Since eval
is used in the same environment, it will have $val
bound, so deferring it works, and since now it's just a variable (with a known name), there are no issues with quoting.
这篇关于在bash间接变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!