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 
4
  • 1
    You seem to be using $b first as a scalar (b=0) and then later as an array (${b[$j]}).CommentedMay 4, 2018 at 9:19
  • What is the significance of the "2" in the title of this question?
    – Kusalananda
    CommentedMay 4, 2018 at 9:33
  • thank you Stephane , how can I declare the array currectly ?
    – Anna
    CommentedMay 4, 2018 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.CommentedMay 4, 2018 at 12:57

1 Answer 1

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.

0

    You must log in to answer this question.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.