将用户值存储在数组中,然后使用bash比较这些变量

问题描述 投票:0回答:1
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]:找不到命令完成

arrays bash loops
1个回答
1
投票

从头开始

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,因为$ia数组中的一个值。或重写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
© www.soinside.com 2019 - 2024. All rights reserved.