简体   繁体   中英

Error [: ==: unary operator expected in shell script

I am trying to run shell script in which I am matching two string values but getting above error. Can you please help me how to resolve this?

Example:

run command:

sh script.sh AMPIL Group_1

So here Group_1 is a Execution_order

I am using below shell script:

    if [ $Execution_Order == "Group_1" ]
    then
        rm sqoop_queries_meta_data_Group_1.txt
        echo $sqoop_queries >> sqoop_queries_meta_data_Group_1.txt
    elif [ $Execution_Order == "Group_2" ]
    then
        rm sqoop_queries_meta_data_Group_2.txt
        echo $sqoop_queries >> sqoop_queries_meta_data_Group_2.txt
    else 
        rm sqoop_queries_meta_data.txt
        echo $sqoop_queries >> sqoop_queries_meta_data.txt
    fi

If else part is not working and giving the above error. Can you please correct me?

The string comparison operator of the test command, (ie the [... ] syntax is defined as a single equals sign. Some shells (including bash ) also accept the double-equals but it's not part of the original POSIX spec.

Thus, you might want to change your queries to:

if [ "$Execution_Order" = "Group_1" ]
then
    rm sqoop_queries_meta_data_Group_1.txt
    echo "$sqoop_queries" >> sqoop_queries_meta_data_Group_1.txt
elif [ "$Execution_Order" = "Group_2" ]
then
    rm sqoop_queries_meta_data_Group_2.txt
    echo "$sqoop_queries" >> sqoop_queries_meta_data_Group_2.txt
else 
    rm sqoop_queries_meta_data.txt
    echo "$sqoop_queries" >> sqoop_queries_meta_data.txt
fi

I don't see why you need an elif in this special example. Also, I don't understand why you first remove a file and then append to that very file. How about

eo="${Execution_Order:+_$Execution_Order}"
echo "$sqoop_queries" > "sqoop_queries_meta_data$eo.txt"

? The main difference is that if Execution_Order would be, say, Group_3, it would create a file sqoop_queries_meta_data_Group3 in my solution, while it would write to sqoop_queries_meta_data.txt in your attempt, but if this is a problem in your context, this can easily be fixed.

Explanation: The :+ sets eo to empty, if Execution_Order is empty, and to _$Execution_Order otherwise.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM