开发者

Call variable based on content of another variable possible in BASH?

Let's say, I have 3 variables, A=1, B=2, C=3 and finall开发者_如何学Cy a last variable containing the name of either of them (VAR=A). Is it possible to call A, B, C based on VAR's content without 'if's?

Like echo "${$VAR}"?


Yes.

eval echo \$$VAR

There is also a bash-only way of doing this, using indirect reference:

echo ${!VAR}


A=1
B=2
C=3
VAR=B
echo ${!VAR}

Output:

2

Documentation (man bash):

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜