0

I have two variables:

dateTimeNow=$(date -d 'now' +"%Y/%m/%d %H:%M:%S")
tokenExpireDate=$(date -d 'now + 25 minutes' +"%Y/%m/%d %H:%M:%S")

I want to check if $tokenExpireDate <= than $dateTimeNow

Something like this

if [[ "${tokenExpireDate}" <= "${dateTimeNow}" ]]; then echo "hi"; fi

I got:

-bash: syntax error in conditional expression
-bash: syntax error near `"${dateTimeNow}"'
bmoreira18
  • 143
  • 8

2 Answers2

6

I'm not sure if you could compare strings like that, but you can compare the total seconds of the 2 dates:

dateTimeNow=$(date -d 'now' +%s)
tokenExpireDate=$(date -d 'now + 25 minutes' +%s)

And then use the -le and -ge operators for comparison:

if [[ ${tokenExpireDate} -ge ${dateTimeNow} ]]; then echo "hi"; fi
  • Bash 4.2+ has; `printf -v dateTimeNow '%(%s)T'; tokenExpireDate=$((dateTimeNow + 25 * 60))`, to capture both timestamps without spawning a sub-shell or running an external tool. – Léa Gris Jun 23 '21 at 15:58
1

There's no <= operator, just < and >.

Since <= is the same as not >, you can simply reverse the comparison and invert the test.

if [[ !("${tokenExpireDate}" > "${dateTimeNow}") ]]; then echo "hi"; fi
Barmar
  • 741,623
  • 53
  • 500
  • 612