Stuart
Stuart

Reputation: 51

If date string is + or - 5 minutes then

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

I want to do a check to see if the date stamp of a file is + or - 5 minutes from the time now. I have so far:

#!/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 datestamp of the file (MODDATE) and the date now + or - 5 minutes.

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

Thank you for all of your help in advance

Upvotes: 4

Views: 1280

Answers (2)

gniourf_gniourf
gniourf_gniourf

Reputation: 46883

How about you don't try to parse the output of stat and directly take its output in seconds since Epoch with %Y? It would then be easier to use Bash's arithmetic.

Your script would look like this (with proper quoting, modern Bash constructs and lowercase variable 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

Upvotes: 2

fedorqui
fedorqui

Reputation: 290215

I recommend you to use date %s to have the date in seconds since 1/1/1970 and make date comparison much easier.

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

Hence,

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

should make it.

Or even shorter:

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

Upvotes: 3

Related Questions