I'm trying to see if a timestamp is expired. Which it would be, if it's before now or empty.
exp=1662023095
NOW=$(date %s)
if [[ -z $exp || (($exp < $NOW)) ]]; then
echo "Update token..."
else
echo "Token still valid!"
fi
The always echo "Update token...". Can someone tell me what I'm doing wrong?
CodePudding user response:
found in the man bash
:
When used with [[, the < and > operators sort lexicographically using the current locale.
Give this a try (edited following the @user1934428 comment below)
if [[ -z $exp ]] || (( exp < NOW )) ; then
...
CodePudding user response:
The ((...))
doesn't make sense inside [[...]]
, but you can make it still simpler: If you write it without using $
, i.e. as
if (( exp < NOW ))
then
...
fi
you don't need to test for an empty exp
anymore, because exp
would then be interpreted as if it were zero.
CodePudding user response:
You are setting the exp to old time: exp=1662023095 which is always less than the current time
date " %s"
Sample script:
cat "./73566778.sh"
#!/bin/bash
let exp=1662023095
echo "exp: $(echo "scale=5;$exp / ( 60 * 60 * 24 * 365)" | bc -q) Years"
let NOW=$(date %s)
echo "1662023095 seconds is always less than current second $NOW"
echo "NOW: $(echo "scale=5;$NOW / ( 60 * 60 * 24 * 365)" | bc -q) Years"
echo "if [[ -z $exp || $exp -lt $NOW ]]"
if [[ -z $exp || $exp -lt $NOW ]]
then
echo "Update token..."
else
echo "Token still valid!"
fi
Output:
$ ./73566778.sh
exp: 52.70240 Years
1662023095 seconds is always less than current second 1662025519
NOW: 52.70248 Years
if [[ -z 1662023095 || 1662023095 -lt 1662025519 ]]
Update token...
Hence this will always display: Update token...
Based on your comment:
I'm trying to see if a timestamp is expired. You have to write other script which is having exp data exp=... to update current script.