If the date string is + or - 5 minutes, then

I am new to bash scripts and trying to work with an if statement.

I want to check to see if there is a + or - 5 minutes file date stamp from the point in time. I still:

#!/bin/bash MODDATE=$(stat -c '%y' test.txt) echo moddate= $MODDATE MODDATE=$(echo $MODDATE |head --bytes=+16) echo now = $MODDATE currentdate2=$(date -d "+5 minutes" '+%Y-%m-%d %H:%M') currentdate3=$(date -d "-5 minutes" '+%Y-%m-%d %H:%M') echo currentdate2 = $currentdate2 echo currentdate3 = $currentdate3 

So this gives me the file date (MODDATE) and the date is now + or - 5 minutes.

How can I do an IF statement to say "if $ MODDATE is between $ currentdate2 (+5 minutes from now) and $ currentdate3 (after -5 minutes)" then echo [1]> output.txt ELSE echo [0] > output.txt.

Thanks for your help in advance.

+4
source share
2 answers

How about you not trying to parse stat output and directly output it in seconds since Epoch using %Y ? Then it would be easier to use Bash arithmetic.

Your script will look like this (with proper quoting, modern Bash constructs, and lowercase names):

 #!/bin/bash moddate=$(stat -c '%Y' test.txt) echo "moddate=$moddate" now=$(date +%s) if ((moddate<=now+5*60)) && ((moddate>=now-5*60)); then echo "[1]" > output.txt else echo "[0]" > output.txt fi 
+2
source

I recommend that you use date %s to have a date in seconds since January 1, 1970 and greatly simplify date comparisons.

 currentdate2=$(date -d "+5 minutes" '+%s') currentdate3=$(date -d "-5 minutes" '+%s') 

Hence,

 if [ $moddate -ge $currentdate2 ] && [ $moddate -le $currentdate3 ]; then .... fi 

gotta do it.

Or even shorter:

 [ $moddate -ge $currentdate2 ] && [ $moddate -le $currentdate3 ] && echo "in interval!" 
+3
source

Source: https://habr.com/ru/post/1489529/


All Articles