0
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

2
  • 1
    First thing , Learn to quote your variables. $(a[$i]) is a command substituion, What are you really trying to do? c Commented Feb 6, 2020 at 0:41
  • for i in ${a[@]} will iterate over the values in the array, not its indexes; that is, if the array is a=(100 507 12), then i will be set to 100, then 507, then 12. So you want echo "$i" instead of echo ${a[$i]} (let alone echo ${a[$i]} which, as @Jetchisel pointed out, does something completely different). Commented Feb 6, 2020 at 6:06

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.