Search code examples
arraysbashbubble-sort

Getting "line 11: [: 9: unary operator expected"


I was writing this simple Bubble Sort code in Bash and I faced this strange error. Although I am getting the correct output, this error keeps bugging me.

Output

Enter the array elements: 9 4 1 2 3 0 4 5
Array elements: 
9  4  1  2  3  0  4  5  
bubble.bash: line 11: [: 9: unary operator expected
Sorted Array elements: 
0  1  2  3  4  4  5  9  

The Code:

#!/bin/bash
read -p "Enter the array elements: " -a arr
echo "Array elements: "
for elem in ${arr[@]}
do 
    echo -ne "$elem  "
done
echo
for (( i = 0; i <= ${#arr[@]}-1; i++ )); do
    for (( j = 0; j <= ${#arr[@]}-$i-1; j++ )); do
        if [ ${arr[j]} -gt ${arr[j+1]} ]; then
            t=${arr[$j]}
            arr[$j]=${arr[$j+1]}
            arr[$j+1]=$t
        fi
    done 
done
echo "Sorted Array elements: "
for elem in ${arr[@]}
do 
    echo -ne "$elem  "
done
echo

Solution

  • Change the line for (( i = 0; i <= ${#arr[@]}-1; i++ ));

    to: for (( i = 0; i < ${#arr[@]}-1; i++ ));

    and for (( j = 0; j <= ${#arr[@]}-$i-1; j++ ))

    to: for (( j = 0; j < ${#arr[@]}-$i-1; j++ ))