1

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?

Program:

#!/bin/sh

latest_sum_check=10101;

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

    echo $EXISTING_SUM_CHECK;
    echo "Please process";
else
    echo "Do not process"
fi
Rajez
  • 11
  • 1
  • 2

2 Answers2

2

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.

ilkkachu
  • 138,973
1

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
    EXISTING_SUM_CHECK=$latest_sum_check
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.