动态变量引用

动态变量引用

如果我要访问via的内容,我想定义一个my_stacklist值为so 的变量。{mypc}_stacklistmypc=kastkast_stacklistmy_stacklist

我认为这与我之前关于动态变量的问题相同,但无法用declareor修复它eval

我在具有最新操作系统的 RPi 4 上使用 bash。

# want to have a my_stacklist for the current mypc and associating stacklist {mypc}_stacklist
mypc=kast
kast_stacklist=( stack1 stack2 stack3 stack4 )
screen_stacklist=( stack1 stack2 stack3 )

# First attempt
xxxx=$(eval "echo ${mypc}_stacklist") 
my_stacklist=$(eval "echo \$$xxxx")
printf "my_stacklist=${my_stacklist[@]}"

# Second attempt
#declare -n my_stacklist2=${xxxx[@]}        
declare -n my_stacklist2=${xxxx}        
printf "my_stacklist=${my_stacklist[@]}"
# i only get the first item instead of all items

答案1

使用名称参考:

mypc=kast
kast_stacklist=(k1 k2 k3)
other_stacklist=(o1 o2 o3)

declare -n mystacklist="${mypc}_stacklist"

for i in "${!mystacklist[@]}"; do
  printf '%d\t%s\n' $i "${mystacklist[i]}"
done
0   k1
1   k2
2   k3

相关内容