while read line
do
if [ $line -ge $zero ]
then
a+=($line) ##here I am attempting to store the values in an array
else
for i in ${a[@]}
do
echo $(a[$i]) ## here I am trying to print them
done
fi
出了什么问题?它给出了这个错误:
a [1]:找不到命令
a [2]:找不到命令
a [3]:找不到命令完成
从头开始
if [ $line -ge $zero ]
$line
中应使用哪种数据类型?-ge
用于数字比较。如果$line
是字符串而不是使用=
,或者您只是想检查它是否不为空,请使用以下语法if [[ "$line" ]]
下一个。
a+=($line)
同样,如果$line
是一个字符串,那么您应该像这样将“”换成a + =(“ $ line”)因为行可以包含空格。对于循环。
for i in ${a[@]}
do
echo $(a[$i]) ## here I am trying to print them
您在这里弄乱语法for i in ${a[@]}
将遍历数组值,而不是索引。再次,如果值是字符串,则像这样for i in "${a[@]}"
使用“”因此,由于以下两个原因,此echo $(a[$i])
无效。首先,您应该在此处使用{},例如echo ${a[$i]}
,第二个$i
不是索引,但是如果它是数字但使用错误的方式,则实际上可以工作。因此,这里您只需要echo $i
,因为$i
是a
数组中的一个值。或重写foor循环。
for i in ${!a[@]}
do
echo ${a[$i]} ## here I am trying to print them
done
最后但并非最不重要的一点是,该脚本的末尾没有done
还是仅仅是一部分?因此在中,它应该看起来像这样。
while read line; do
if [[ $line ]]; then
a+=( "$line" ) ##here I am attempting to store the values in an array
else
for i in ${!a[@]}; do
echo ${a[$i]} ## here I am trying to print them
done
fi
done < data.txt
echo ${a[@]} # print rusult