1

I have a code, which gives [: -gt: unary operator expected, when the value is empty.

Can anyone please suggest or correct me where I'm wrong ?

if [ -e $POSFile ]; then 
  # Read last Position
  lastPosition=`cat $POSFile`
fi
fileLength=`stat -c %s $LogFile`

if [ $lastPosition -gt $fileLength ]; then
  # Log file rolled
  lastPosition=0
fi

difference=`expr $fileLength - $lastPosition`
Teun Vink
  • 2,465
  • 17
  • 19

1 Answers1

1

There is a possibility that when reaching this logic:

if [ $lastPosition -gt $fileLength ]

either $lastPosition or $fileLength will be empty:

  • $lastPosition may be empty if $POSFile does not exist or cannot be read.
  • $fileLength may be empty if $LogFile does not exist or cannot be read.

Try using quotes like this:

if [ "$lastPosition" -gt "$fileLength" ]

to force each of those variables to be recognized as a single entity, even if it was empty. Empty variables will be counted as zero in this case (i.e. paired with "greater than" operator).

Note: This proposed solution does not cover the possibility if either variables is recognized as non-number.

aff
  • 370