dross
dross

Reputation: 1759

How do I properly set this variable?

I want to read a epoch time stamp from a file and then compare it with the current epoch time.

The comparison is not working and I get error:

./script.sh: line 13: 1559122886- : syntax error: operand expected (error token is "- ")

#!/bin/bash
RSTL=restart.log
if [ -f $RSTL ]; then
    while IFS='|' read -r NRST LRST
    do
        echo "NRST is: $NRST"
        echo "LRST is: $LRST"
    done <$RSTL
CTIME=$(date +"%s")
echo "CTIME is: $CTIME"
fi
#LRST=$(date +"%s")
DIFF=$(( $CTIME-$LRST ))
echo "DIFF is: $DIFF"
if [[ $DIFF -gt 86400 ]]; then
    echo "1|GREATER"
    echo "1|$CTIME" > $RSTL
elif [[ $LRST -lt 86400 ]]; then
    echo "LESS THAN"
    echo "2|$CTIME" > $RSTL
else
    echo "1|NEW"
    echo "0|$CTIME" > $RSTL
fi
exit

Upvotes: 0

Views: 52

Answers (2)

oguz ismail
oguz ismail

Reputation: 50785

When you mention an undeclared variable in $((..)) in variable expansion form (like $var), it expands to empty string instead of zero, thus the error you get. Don't use variable expansions in arithmetic expansions unless you have to. Change 13th line to following and you're good to go.

DIFF=$((CTIME-LRST))

Another issue with your script is, you're populating NRST and LRST in a while loop, and this way those are unaccessible outside the loop. To fix it, replace the while loop with:

IFS='|' read -r NRST LRST <"$RSTL"
echo "NRST is: $NRST"
echo "LRST is: $LRST"

And don't forget quoting all variable expansions to avoid word splitting.

Upvotes: 2

rblock
rblock

Reputation: 58

In line 12 remove "#" and in line 13 remove "$" from $CTIME and $LRST.

#!/bin/bash
RSTL=restart.log
if [ -f $RSTL ]; then
    while IFS='|' read -r NRST LRST
    do
        echo "NRST is: $NRST"
        echo "LRST is: $LRST"
    done <$RSTL
CTIME=$(date +"%s")
echo "CTIME is: $CTIME"
fi
LRST=$(date +"%s")
DIFF=$(( CTIME-LRST )) # Remove $ from $CTIME and $LRST
echo "DIFF is: $DIFF"
if [[ $DIFF -gt 86400 ]]; then
    echo "1|GREATER"
    echo "1|$CTIME" > $RSTL
elif [[ $LRST -lt 86400 ]]; then
    echo "LESS THAN"
    echo "2|$CTIME" > $RSTL
else
    echo "1|NEW"
    echo "0|$CTIME" > $RSTL
fi
exit

Upvotes: 1

Related Questions