Bash - 在数组中打印变量的值

时间:2021-12-02 15:41:25

I want to do something like this

我想做这样的事情

A='123'
B='143'
C='999'

declare -a arr=(A B C)

for i in "{$arr[@]}"
do
     echo "@i" "$i" 
done

Which should give me the output of

哪个应该给我输出

A 123
B 143
C 999

But instead I receive the variable names, not the value in the output (I just see "A @i" in the output...

但我得到的是变量名,而不是输出中的值(我只是在输出中看到“A @i”...

2 个解决方案

#1


2  

If you want to store the variable names in the loop, rather than copy their values, then you can use the following:

如果要将变量名存储在循环中,而不是复制它们的值,则可以使用以下命令:

for i in "${arr[@]}"; do
    echo "${!i}"
done

This means that the value of i is taken as a name of a variable, so you end up echoing $A, $B and $C in the loop.

这意味着i的值被视为变量的名称,因此您最终会在循环中回显$ A,$ B和$ C.

Of course, this means that you can print the variable name at the same time, e.g. by using:

当然,这意味着您可以同时打印变量名称,例如通过使用:

echo "$i: ${!i}"

It's not exactly the same, but you may also be interested in using an associative array:

它不完全相同,但您可能也对使用关联数组感兴趣:

declare -A assoc_arr=( [A]='123' [B]='143' [C]='999' )

for key in "${!assoc_arr[@]}"; do
    echo "$key: ${assoc_arr[$key]}"
done

#2


1  

I suggest to add $:

我建议添加$:

declare -a arr=("$A" "$B" "$C")

#1


2  

If you want to store the variable names in the loop, rather than copy their values, then you can use the following:

如果要将变量名存储在循环中,而不是复制它们的值,则可以使用以下命令:

for i in "${arr[@]}"; do
    echo "${!i}"
done

This means that the value of i is taken as a name of a variable, so you end up echoing $A, $B and $C in the loop.

这意味着i的值被视为变量的名称,因此您最终会在循环中回显$ A,$ B和$ C.

Of course, this means that you can print the variable name at the same time, e.g. by using:

当然,这意味着您可以同时打印变量名称,例如通过使用:

echo "$i: ${!i}"

It's not exactly the same, but you may also be interested in using an associative array:

它不完全相同,但您可能也对使用关联数组感兴趣:

declare -A assoc_arr=( [A]='123' [B]='143' [C]='999' )

for key in "${!assoc_arr[@]}"; do
    echo "$key: ${assoc_arr[$key]}"
done

#2


1  

I suggest to add $:

我建议添加$:

declare -a arr=("$A" "$B" "$C")