0

I'm just learning bash scripting. Tried to sort the array, it says "integer expression expected for lines 10 and 15. What am I doing wrong? Here is my script:

#!/bin/bash
array=('5' '9' '0' '20' '2' '15' '6' '25' '1')
b=0
n=${#array[@]}
i=0
while [ "$i" -lt "$n" ]
do
    c=${array[$i]}
    d=${array[$i+1]}
    if [ "$c" -lt "$d" ]; then
        j=0
        while [ "$j" -le "$i" ]
        do
            f=${b[$j]}
                if [ "$f" -gt "$c" ];
                    then b[$j]=$c
                    echo "${b[$j]}"
                fi
            j=$(( j+1 ))
        done
    fi
    i=$(( i+1 ))
done
  • 1
    You seem to be using $b first as a scalar (b=0) and then later as an array (${b[$j]}). – Stéphane Chazelas May 4 '18 at 9:19
  • What is the significance of the "2" in the title of this question? – Kusalananda May 4 '18 at 9:33
  • thank you Stephane , how can I declare the array currectly ? – Anna May 4 '18 at 9:52
  • 1
    Running your script with bash -x ./the-script should make it apparent what the problem is. Again, look at your usage the $b variable. – Stéphane Chazelas May 4 '18 at 12:57
3

You're calling the [ command with the -lt/-gt decimal integer comparison operators on operands that are not always decimal integers.

You can see what happens if you run the script with bash -x. You'll see things like:

+ f=
+ '[' '' -gt 0 ']'
./myscript: line 15: [: : integer expression expected

With:

while [ "$i" -lt "$n" ]
do
[...]
   d=${array[$i+1]}

On the last pass in that loop, you'll try to access beyond the last element of the array, so $d will be empty.

You're also initialising $b as a 0 string, and later on accessing it as an array. See also how f=${b[$j]} will get you an empty $f except for when $j is 0.

I don't know what you're trying to do with that code, but it seems like you need to go back to the drawing board.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.