Eliminating the Error Message ‘Unary Operator expected’ in Shell Scripting

Titled “an introductory guide to robust filename handling and other string passing in shell scripts”, it’s recommended to use (( )) for math operations to improve code readability without special symbols. This solution can be found on the GitHub page for shellcheck under the code SC2219. The problematic area in your code can be replaced with an improved version.


Solution:

For better readability of code, one can use (( )) instead of using special symbols for math operations. Refer to the link https://github.com/koalaman/shellcheck/wiki/SC2219 for more information.

Your issue location has been identified as

if [ ${array[j]} -gt ${array[$((j+1))]} ]

and requires replacement using

if (( array[j] > array[j+1] ))

.

Improved version of your code :

#!/bin/bash
declare -a array 
declare hold=0
# echo "Input length of array: " 
#read length
#for (( i = 0; i < length; i++ )); do 
#   echo "Enter array number: $i" ;
#   read input 
#   array+=($input) 
# done
array=(6 7 2 3 8 9)
length=${#array[@]}
echo "************************"
echo "Elements in array: " 
echo "${array[*]}"
echo "************************"
for (( i = 0; i < length; i++ )); do    
    
    for (( j = 0; j < length -1 ; j++ )); do         
        #echo "iteration i/j - $i/$j ${array[*]} "                      
        if (( array[j] > array[j+1] )); then            
            hold=array[j]
            array[j]=array[j+1]
            array[j+1]=hold
            echo "change ${array[*]} " 
        fi 
    done 
done
echo "************************"
echo "Sorted Elements in array: " 
echo "${array[*]}"
echo "************************"

Frequently Asked Questions