1

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".

  • wear bigboy pants and use `if [ X”$str1” = X”$str2” ] ; then doit ; fi‘ like they do in FreeBSD base scripts – user2497 Feb 22 at 20:30
2

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
1

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"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.