0

I am trying to test a date ...if it's between those 2 time frames i want to print them... But i get errors..This is my script

today_time=$(date +%H:%M:%S --date '-1 sec')
today_dow=$(date +"%u")

today_less=$(date +%H:%M:%S --date '-1 min')
today_more=$(date +%H:%M:%S --date '+1 min')
echo $today_less
echo $today_time
echo $today_more

if [ $today_less -gt $today_time ] && [ $today_time -lt $today_more ]; then
        echo "$today_less"
        echo "$today_time"
        echo "$today_more"
else
        echo no
fi

I have tried -ge with -le and gives me: Integer expression expected -gt and -lt: Integer expression expected I also used '<' and '>' and gives me: No such file or directory.

I need to make this work with time dates only...not with int

Cause the time i will extract it from the db and replace today_time with the time from db.

Omega
  • 277
  • 3
  • 20
  • Possible duplicate of https://stackoverflow.com/questions/8116503/how-to-compare-two-datetime-strings-and-return-difference-in-hours-bash-shell – tripleee Dec 18 '17 at 11:10

1 Answers1

2

Your output is not the digits, but strings like:

[sahaquiel@sahaquiel-PC ~]$ date +%H:%M:%S --date '-1 min'
13:40:30

Convert it to Unixtime and compare clear numbers, for example:

today_time=$(date +%H:%M:%S --date '-1 sec')
today_time_u=$(date +%s --date '-1 sec')

today_dow=$(date +"%u")  

today_less=$(date +%H:%M:%S --date '-1 min')
today_less_u=$(date +%s --date '-1 min')

today_more=$(date +%H:%M:%S --date '+1 min')
today_more_u=$(date +%s --date '+1 min')

echo $today_less
echo $today_time
echo $today_more

if [ $today_less_u -gt $today_time_u -a $today_time_u -lt $today_more_u ]; then
        echo "$today_less"
        echo "$today_time"
        echo "$today_more"
else
        echo no
fi

And once more, in your example, $today_less is current date - 1 minute; $today_time is current date - 1 second; So, $today_time > $today_less every time and your if [ $today_less_u -gt $today_time_u part will be false every time, so you will not be able get anything but echo no in else statement.

Viktor Khilin
  • 1,760
  • 9
  • 21
  • thank you for help...it works...didn't thought of converting them – Omega Dec 18 '17 at 10:55
  • 1
    Enjoy. Btw, in bash, use `-a` instead of `&&` and `-o` instead of `||` in `if/while` statements. – Viktor Khilin Dec 18 '17 at 10:57
  • i just substitute the today_time as an example...to test the if before applying it to the real script...cause the actual time i ll get it from the DB and convert it – Omega Dec 18 '17 at 10:58