Check if a variable is zero

I have seen many posts for this sort of problem but I just did not know how to use it for my issue. A number is assigned to a variable and I wanted to check if it is a zero or non zero.

Example of my numbers are below:
000000000000000000000000000000000000000000000000
574E47303030303030303030303030303030303135313937

So "000000000000000000000000000000000000000000000000" is considered as zero and the other as non zero right, but how would I do that using IF statement?

The following is my script

The following is my output saying that the number "574E47303030303030303030303030303030303135313937" is not valid for the command.

Please let me know if there are any suggestions on this.
Thank you!!


  1. \t ↩ī¸Ž

$ [ '000000' -eq 0 ] && echo zero || echo NONzero
zero

$ [ '100000' -eq 0 ] && echo zero || echo NONzero
NONzero

Those numbers, if they were treated as number or hex numbers overflow the limits of POSIX shell arithmetic. However strings are different.

#!/bin/ksh
iszero()   # print 1 if zero,  0 else
{
     ok=$(echo "$1" | tr -d '0')
     if [ -z "$ok" ] ; then
        print 1
     else
        print 0
     fi
}
a=574E47303030303030303030303030303030303135313937
b=000000000000000000000000000000000000000000000000
echo "$a  result: $(iszero $a)"
echo "$b  result: $(iszero $b)"

I have very random numbers like "574E47303030303030303030303030303030303135313937", it is not the same number all the time. It varies. These are the correlation Id's of the MQ messages. So I cant really Hard code the numbers. and I i use the code above I am still getting the same error.

This was meant as a hint and not as a complete solution.
Follow Jim's suggestion as it deals with integer overflow.

Thank you!!

The problem is you are testing with -eq which denotes a number.

This works in ksh.

#!/bin/ksh
 
func1()
{
   var="574E47303030303030303030303030303030303135313937"
   echo "$var"
}
 
 
ret=$(func1)
if [ "$ret" != 0 ]           ## change your test to != instead of -eq
then
        echo "Null"
else
        echo "Not Null"
fi
return 0
1 Like

I guess this is what I was looking for...Thank you!! That really helped.

Lateral thought approach which works with most shells.
Treat the long number as a string (as previous posters advise) and check whether all the characters are zero by removing all zero characters.

var="000000000000000000000000000000000000000000000000"
if [ -z "`echo $var|tr -d '0'`" ]
then
        echo "NULL"
fi
#
var="574E47303030303030303030303030303030303135313937"
if [ ! -z "`echo $var|tr -d '0'`" ]
then
        echo "NOT NULL"
fi