我是bash脚本的新手,我想知道为什么我收到上述消息。我尝试一个来自for循环的算术值,然后我想打印数组。任何人都可以帮助我吗?
提前谢谢!!
#!/bin/bash
declare -a SCORES
for j in `seq 0 5`;
do
SCORES$j="$(sh myscript.sh $DSLAM $j | grep "" -c )"
done
for k in "${SCORES[@]}"
do
echo "message $'\t' $SCORES$k"
done
echo ${#SCORES}
=======
输出
abcd.sh: line 16: SCORES0=3: command not found
abcd.sh: line 16: SCORES1=135: command not found
abcd.sh: line 16: SCORES2=826: command not found
abcd.sh: line 16: SCORES3=107: command not found
abcd.sh: line 16: SCORES4=3: command not found
abcd.sh: line 16: SCORES5=3: command not found
0
答案 0 :(得分:4)
您不能使用在运行时生成的名称来分配变量;至少不是你尝试的方式。
您有以下选项:
declare "SCORES$j=$(sh myscript.sh $DSLAM $j | grep '' -c )" # creates new variables like SCORES1, SCORES2 etc.
eval "SCORES$j=$(sh myscript.sh $DSLAM $j | grep '' -c )" #Definitely not preferred.
SCORES[$j]="$(sh myscript.sh $DSLAM $j | grep '' -c )" #uses array you have created.
最有可能的是,选项3就是你想要的。