Passant
Passant

Reputation: 11

storing user values in an array then comparing these variables using bash

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

what is going wrong? it is giving this error:

a[1]: command not found

a[2]: command not found

a[3]: command not found done

Upvotes: 0

Views: 38

Answers (1)

Ivan
Ivan

Reputation: 7277

From the begining

if [ $line -ge $zero ]

what data type should be in $line? -ge used in numeric comparison. If $line is a string than use = or if you just wnt to check that it's not empty use this syntax if [[ "$line" ]] Next.

a+=($line)

Again if $line is a string then you should wrap in "" like this a+=("$line") coz line can contain spaces. For loop.

  for i in ${a[@]}
  do

 echo $(a[$i]) ## here I am trying to print them

You'r messing with syntax here for i in ${a[@]} will iterate over arrays values, not indexes. And again if values are strings use "" like this for i in "${a[@]}" So this echo $(a[$i]) won't work by 2 reasons. First you should use {} here, like this echo ${a[$i]}, second $i is not index, but it's may actualy work if it's a digit but in a wrong way. So here you need just echo $i coz $i is alredy a value from a array. Or rewrite foor loop.

for i in ${!a[@]}
do
    echo ${a[$i]} ## here I am trying to print them
done

And last but not least, there is no done at the end of this script or it's just a part? So in the and it should look like this.

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

Upvotes: 1

Related Questions