[: -gt: unary operator expected
5,468
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.
Related videos on Youtube
Author by
user324391
Updated on September 18, 2022Comments
-
user324391 over 1 year
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`