6

I am trying to compare todays date with the last modified date from a file.

DATE=$(date +"%F")

LASTMOD=$(stat $i -c %y);
LASTMOD_DATE=$(cut -d' ' -f1 <<<"$LASTMOD")

if [ "$LASTMOD_DATE" -ge "$DATE" ]; then
    printf "%-19s | " "$DATE"
else
    printf "%-19s | " "NO RECENT MOD"
fi

Currently this does not compare them properly and I think it's because LASTMOD_DATE is not actually a datetime so I get the error: "integer expression expected".

0

2 Answers 2

5

You can use the timestamp format date +%s and the -r option.

-r, --reference=FILE
         display the last modification time of FILE

like

if [ $(date +%s -r file) -ge $(date +%s) ]; then 
    # do something
fi
0
4

The best way to compare points of time (dates) is in seconds (since Epoch).

Changing the %y to %Y for stat will give the modification date of the file in seconds:

fileModifiedOn=$(stat $i -c %Y)

Today's date could be read either with (GNU) date with the format %s:

todayDate=$(date +'%s')

or, in Bash 5.0, with the variable EPOCHSECONDS:

todayDate=$EPOCHSECONDS

or, in older bash, with a (builtin) printf format:

todayDate=$(printf '%(%s)T')

Then, it is just a matter of a simple integer comparison:

if [[ "$fileModifiedOn" -gt "$todayDate" ]] then
    result=$todayDate
else
    result="NO RECENT MOD"
fi

printf "%-19s | " "$result"

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.