不,这是不可能的,你试试它的方式。首先,名称中不允许使用[]
(请参阅手册中的definitions),因此您必须使用名称line${a}position$b
。
一(mostly frowned upon)选项是使用eval
:
#!/bin/bash
for ((a=1; a<=2; a++)); do
for ((b=1; b<=2; b++)); do
varname=line${a}position$b
eval $varname=\"This is LINE \$a at POSITION \$b.\"
echo "${!varname}"
done
done
这首先创建将被用作变量名,varname
的字符串。对于每个循环,它变成line1position1
,line1position2
等等。
然后,在这条线,我们会将您的字符串分配到与该名称的变量:
eval $varname=\"This is LINE \$a at POSITION \$b.\"
的报价是这样的字符串进行扩展,例如在第一循环中,
line1position1="This is LINE $a at POSITION $b."
和line1position1
的值变为This is LINE 1 at POSITION 1.
。
要访问该变量的值,我们必须使用indirect expansion:在${!varname}
的!
表明varname
不是我们想要的变量名,但扩展它。
这一切都这样说,猛砸4.3推出namerefs,这让这个更完美地解决:
#!/bin/bash
for ((a=1; a<=2; a++)); do
for ((b=1; b<=2; b++)); do
declare -n refvar=line${a}position$b
refvar="This is LINE $a at POSITION $b."
echo "$refvar"
done
done
没有eval
这里需要。
两种解决方案的输出是这样的:
This is LINE 1 at POSITION 1.
This is LINE 1 at POSITION 2.
This is LINE 2 at POSITION 1.
This is LINE 2 at POSITION 2.