I am running the below script which throws me an errors with unary operator issue. In the main shell script program, I will be using this existing_sum_check variable down the line but I want to perform this check anyhow. How can I avoid this error?




if [ $latest_sum_check != $EXISTING_SUM_CHECK ]; then
    EXISTING_SUM_CHECK = $latest_sum_check;

    echo "Please process";
    echo "Do not process"

You have essentially [ something != $bar ].

If $bar is empty, that turns into if [ something != ], which of course doesn't work, since the equality test requires two operands. Though at least Bash's test/[ has a funny way of stating that: apparently it checks the number of arguments, and since there's only two expects the first to be a unary operator. The something there isn't one, so it complains.

So, put quotes around the variables:

if [ "$latest_sum_check" != "$EXISTING_SUM_CHECK" ]; then ...

And this runs a command EXISTING_SUM_CHECK with the equals sign and whatever comes from the expansion of the variable as parameters:

 EXISTING_SUM_CHECK = $latest_sum_check;

Variable assignments in the shell don't take spaces around them.


This is an error condition of your test due to having an undeclared variable $EXISTING_SUM_CHECK. You should have another check such as:

if [ -z $EXISTING_SUM_CHECK ]; then
elif [ $latest_sum_check != $EXISTING_SUM_CHECK ]; then

This uses a unary operation to check if the string has zero length. != requires that both sides of the test have a non-empty value.

Another way to solve this can be:

if [ "X${latest_sum_check}" != "X${EXISTING_SUM_CHECK}" ]; then

Which forces both values to have a value of at least X if the variable is unset or null or ''.

Also to note, typically if you're comparing two numbers -ne is recommended over !=, as != is reserved for strings. However -ne only works for numerals [0-9], and not hexidecimal comparisons such as md5sum results.

  • Also note the extraneous spaces surrounding their assignment statement EXISTING_SUM_CHECK = $latest_sum_check – Jeff Schaller Nov 28 '17 at 17:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.