Bash – Test if File was Modified After Date in File Name

bashfilesosxtimestamps

I have a files named with YYYYMMDD in the file name, such as

file-name-20151002.txt

I want to determine if this file was modified after 2015-10-02.

Notes:

  • I can do this by looking at the output of ls, but I know that parsing the output of ls is a bad idea.
  • I don't need to find all files dated after a specific date, just need to test one specific file at a time.
  • I am not concerned about the file being modified on the same date after I created it. That is, I just want to know if this file with 20151002 in the name was modified on Oct 03, 2015 or later.
  • I am on MacOs 10.9.5.

Best Answer

Here are some possible ways with :

  • OSX stat:

    newer () {
    tstamp=${1:${#1}-12:8}
    mtime=$(stat -f "%Sm" -t "%Y%m%d" "$1")
    [[ ${mtime} -le ${tstamp} ]] && printf '%s\n' "$1 : NO: mtime is ${mtime}" || printf '%s\n' "$1 : YES: mtime is ${mtime}"
    }
    
  • GNU date:

    newer () {
    tstamp=${1:${#1}-12:8}
    mtime=$(date '+%Y%m%d' -r "$1")
    [[ ${mtime} -le ${tstamp} ]] && printf '%s\n' "$1 : NO: mtime is ${mtime}" || printf '%s\n' "$1 : YES: mtime is ${mtime}"
    }
    
  • zsh only:

    zmodload zsh/stat
    newer () {
    tstamp=${1:${#1}-12:8}
    mtime=$(zstat -F '%Y%m%d' +mtime -- $1)
    [[ ${mtime} -le ${tstamp} ]] && printf '%s\n' "$1 : NO: mtime is ${mtime}" || printf '%s\n' "$1 : YES: mtime is ${mtime}"
    }
    

Usage:

newer FILE

Example output:

file-name-20150909.txt : YES: mtime is 20151026

or

file-name-20151126.txt : NO: mtime is 20151026
Related Question