Bash script error: integer expression expected

bash

I'm having a rather weird issue, I'm running a script (Bash) on multiple servers and it stopped working on one of the servers (works perfectly fine on all other servers).

Here is the problem part of the script: (I did not write it myself, all credits go to "Rich") (http://www.notrainers.org/monitoring-memory-usage-on-linux-with-nagios-and-nrpe/)

    if [ "$result" -lt "$warn_level" ]; then     #Line 56
    echo "Memory OK. $result% used."
    exit 0;
elif [ "$result" -ge "$warn_level" ] && [ "$result" -le "$critical_level" ]; then  #Line 59
    echo "Memory WARNING. $result% used."
    exit 1;
elif [ "$result" -gt "$critical_level" ]; then   #Line 62
    echo "Memory CRITICAL. $result% used."
    exit 2;
fi

Complete error message:

./check_memory.sh: Line 56: [: 7.: integer expression expected

./check_memory.sh: Line 59: [: 7.: integer expression expected

./check_memory.sh: Line 62: [: 7.: integer expression expected

If you need more info, let me know and I will try to supply it as fast as possible.

Appreciate all inputs 🙂

Best Answer

From the link you provided, I see the below line.

result=$(echo "$used / $total * 100" |bc -l|cut -c -2)

As per @Graeme's comment, change the above line to below.

result=$(echo "$used / $total * 100" |bc -l)

Now, after adding the above line, we have to change the output of the result to integer as below.

result1=${result/.*}

I guess in one of the machines where the error occurs, this output is not an integer. Just convert the output of result to integer so that you can handle such cases. Add the below line after you calculate the result.

result1=${result/.*}

And instead of result change the variable names as result1 inside the if loops, and the error won't occur.

I suspect, the cut -c -2 attributes to the error mostly since it is cutting the first 2 characters only. What if result has just one character? Suppose if result is 1.23456, the above cut will result in 1. as the value for result which obviously is the cause of the integer expected error.

The reason it is working fine in the remaining servers is because it has not encountered a case where the result variable has just a single digit. It is highly likely to fail in the remaining servers too if the result is a single digit variable (something like I mentioned in the above example).

Related Question