if loop not working in BASH shell

i have this code for a simple if loop:

#!/bin/bash
array="1 2 3 4 5"
array2="5 6 7 8 9"
if [ ${array2[0]} -gt ${array[0]} ]; then
echo "${array2[0]} is greater than ${array[0]}!!"
fi

the error is

./script8: line 9: [: too many arguments

./script8: line 9: [: too many arguments

./script8: line 9: [: too many arguments

./script8: line 9: [: too many arguments

./script8: line 9: [: too many arguments

You are assigning the values as a common string to the variables, try this:

array=(1 2 3 4 5)
array2=(5 6 7 8 9)

instead of:

array="1 2 3 4 5"
array2="5 6 7 8 9"

Use:
array=(1 2 3 4 5)
array2=(5 6 7 8 9)

to set up arrays in bash. With the quotes you're putting everything into element zero.

ok thanks that worked..

now i am trying to get some numbers from a .txt file and put them into an array but when i try to echo it i get blank lines...

#!/bin/bash
array=(20 20 20 20 20)
j=0
while [ $j -lt 5 ]
do
awk '/%/' /cygdrive/c/unix/bin.txt | awk '{print $5}'> $[collectbininfo[j]]
echo ${collectbininfo[j]}
echo "$j"
j=`expr $j + 1`
done

bin.txt is the file from which i am picking out the numbers and the line which has the numbers has a % sign.. the file looks like this:

[1] Continuity 32 56%
[2] Continuity 32 56%
[3] Continuity 32 56%
[4] Continuity 32 56%
[5] Continuity 32 56%

i want to put all the 32's in an array

i already used the tr command on the bin.txt file to remove the CR's
thanks for your help guys.. i am still learning unix shell programming..

The 32's are in the 3th field of your file IMO, adjust the field in the awk code if I'm wrong. This is an example how to fill and print an array:

#!/bin/bash

i=0

awk '/%/{print $3}' /cygdrive/c/unix/bin.txt |
while read s
do
  arr[$i]="$s"
  let i=i+1
done

len=${#arr
[*]}
i=0

while [ $i -lt $len ]
do
  echo "${arr[$i]}"
  let i=i+1
done

what is "s"?

The read command assigns the output of the awk command to the shell variable s.

Regards

can i echo this variable s?

also when i try to echo the array it just shows me blank lines on the terminal window..

To learn scripting you need to practice and learn from mistakes to understand the possibilities and know what to expect, so just try it out! :wink:

Regards

you are correct.. thanks for your help.. this is good to get me started..