Getting the number of seconds since a file was modified

It’s quite common on Unix systems to determine whether a file has or has not been modified within a set number of days (usually using the find command) but occasionally you want to know to the second how long ago a file was last modified.

Using a quick call to perl this is easy to achieve:

NUM_SECS=`perl -e '@q=stat($ARGV[0]); print time-$q[9]' <file>`

For an example: Consider the situation where CSV files are FTP’d from another server into a directory for loading into the database. We might have a script that runs every 10 minutes to check for new files and then load them into the database via SQL*Loader. However we need to ensure that we don’t try to process a file which is still in the process of being copied:

# Find all CSV files in the current directory
for FSP in `ls *.csv`
do

  # How long ago was it modified?
  NUM_SECS=`perl -e '@q=stat($ARGV[0]); print time-$q[9]' ${FSP}`

  # If the file has not been modified in the last 30 seconds then assume the transfer is complete
  # and call the FN_load_file function to load it and remove it from the directory.
  if [ ${NUM_SECS} -gt 30 ] ; then
    FN_load_file ${FSP}
  fi;

done