-1

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
  • Let's say arr has 3 elements. When i is 0, j can reach 3-0-1=2. And when j is 2, arr[j+1], i.e arr[3], is empty. Hence the error you're seeing. – oguz ismail Dec 08 '20 at 07:50
  • use if [[ ${arr[j]} -gt ${arr[j+1]} ]] or use double quote on variable. this link could be useful https://stackoverflow.com/questions/13617843/unary-operator-expected-error-in-bash-if-condition – Lety Dec 08 '20 at 07:53
  • 1
    Does this answer your question? ["unary operator expected" error in Bash if condition](https://stackoverflow.com/questions/13617843/unary-operator-expected-error-in-bash-if-condition) – Lety Dec 08 '20 at 07:54
  • Run your script through https://shellcheck.net and implement its suggestions. – Shawn Dec 08 '20 at 08:20

1 Answers1

0

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++ ))