Linux 递增变量编号并指定新值
我试图将列表中的值分配给一组变量。变量编号从1开始,并根据列表中的值数量不断增加。 我为循环快速执行了Linux 递增变量编号并指定新值,linux,shell,variables,Linux,Shell,Variables,我试图将列表中的值分配给一组变量。变量编号从1开始,并根据列表中的值数量不断增加。 我为循环快速执行了,但出现了错误 list="010 110 004" num=0 for node in `echo $list` do ((num+=1)) node_$num="my_host-$node.test.edu.com" echo $node_$num done 但我会遇到这样的错误: bash: node_1=my_host-010.test.edu.com: com
,但出现了错误
list="010 110 004"
num=0
for node in `echo $list`
do
((num+=1))
node_$num="my_host-$node.test.edu.com"
echo $node_$num
done
但我会遇到这样的错误:
bash: node_1=my_host-010.test.edu.com: command not found
1
bash: node_2=my_host-110.test.edu.com: command not found
2
bash: node_3=my_host-004.test.edu.com: command not found
3
如何将列表中的值分配给一组不断增加的变量?在bash
中应该这样做:
list=(010 110 004)
num=0
for node in "${list[@]}"; do
((num+=1))
var="node_$num"
# use declare to create and instanitate var=value
declare "$var"="my_host-$node.test.edu.com"
# examine value o f$var
declare -p "$var"
# or use this echo to print just value
# echo "${!var}"
done
还要注意使用shell数组安全地迭代有限的项目列表。谢谢。但现在我有另一个问题。。。。$var在每次迭代中都会被替换。。我不希望这样,因为我计划在脚本的其余部分使用变量$node_u$num。不,忽略temp$var。您的实际变量node_1、node_2等将可用于脚本的其他部分。我仍然不知道如何在脚本中使用“$var”。例如,如果我想将该变量与其他普通变量放在一个文件中,我应该如何做?此工作是否会响应“$var、$my_other_var1、$my_other_var2”>>/tmp/some_file.out无需在其他任何地方使用$var。您需要在脚本中使用$node_1、$node_2等。我还想知道什么是$my_other_var1
,$my_other_var2
等,因为这些变量没有引用。
declare -- node_1="my_host-010.test.edu.com"
declare -- node_2="my_host-110.test.edu.com"
declare -- node_3="my_host-004.test.edu.com"