Tag Archives: unary operator expected

Script error: unary operator expected [How to Solve]

When the script is executed, the following error appears: “h.sh: Line 9: [: =: unary operator expected”. The specific script is as follows:

[root@Dasoncheng sbin]# cat -n h.sh 
     1	#!/bin/bash
     2	sh -n $1 &>/tmp/err
     3	if [ $?-eq 0 ];
     4	then
     5	    echo "The script is ok"
     6	else
     7	    cat /tmp/err
     8	    read -p "Please input q/Q to exit , or others to edit it by vim: " n
     9	    if [ $n == "q" ] || [ $n == "Q" ];
    10	    then
    11	        exit
    12	    else
    13	        vim $1
    14	        exit
    15	    fi
    16	fi
[root@Dasoncheng sbin]# sh h.sh i.sh 
i.sh: line 3: syntax error: unexpected end of file
Please input q/Q to exit , or others to edit it by vim: 
h.sh: line 9: [: ==: unary operator expected
h.sh: line 9: [: ==: unary operator expected  ##This is the error message that is executed.

Solution:

 if [ $n == "q" ] || [ $n == "Q" ];change to :if [ "$n" == "q" ] || [ "$n" == "Q" ];
##Done!

Because when $n is null (i.e. carriage return does not input any parameters), it becomes [= = q “], which obviously lacks the comparison parameter. When the value of $n is not empty, the script is normal
it can also be avoided by using the following methods:

 if [[ $n == "q" ]] || [[ $n == "Q" ]]
##or
if [ "$n"x == "q"x ] 
##where x can also be other characters.