1

I have a script that checks a directory using mdls* (to sort by added time) and them performs some operations. However, mdls is a bit slow so I’d like to run it only when absolutely necessary (i.e. when directory contents have changed).

My idea is to run mdls once and cache the results, the perform some operation to keep track of the state of the directory. On subsequent runs, I’d run the check operation again and compare the result to what I had. If different, rerun mdls; if not, use the cache.

I’m thinking of either du '/dir/path' | tail -1 (if the directory size remains equal to the byte, it’s likely the contents haven’t changed) or ls '/dir/path' | md5'.

I’m currently more inclined to the md5 solution, since it’s resilient to file renames. However, both of these solutions are hacky, and I wonder if there’s something more efficient (that is still fast).

Ultimately the solution will be used in a ruby script, if that helps.


* I’m not posting this to Ask Different because mdls is not the point. It could be any other slow command.

  • You'll have to define what kind of changes you're interested in. Deleted/added/renamed files surely? What about files within the directory being modified? – ilkkachu Dec 5 '17 at 16:48
  • @ilkkachu I only care for it being accurate to one level (i.e. not recursive). The change I’m interested in is: “are the contents the same?”. – user137369 Dec 5 '17 at 16:53
  • 1
    It's just that added/deleted files update the modification timestamp (mtime) of the directory itself, so for that you don't even need to look at the files. Changes within the files just update the timestamps on the file itself. – ilkkachu Dec 5 '17 at 16:55
  • Yep! That works. Didn’t think to check the directory itself since I was so focused on the contents. Want to add it as an answer so I can accept it? – user137369 Dec 5 '17 at 17:01
1

If it's enough to check for new/deleted files (and ignore modifications to existing files), you can use the timestamp mtime of the directory itself.

You can get it with stat. The output here is in seconds since the start of 1970:

$ stat -f %m "$dir"      # stat on OS X
1512493220
$ stat -c %Y "$dir"      # GNU coreutils stat
1512493801
$ stat -c %.9Y "$dir"    # nanoseconds too
1512493801.802870731

If you want to check modifications to the files, you could check all of their timestamps, and get the largest with e.g. sort:

$ stat -f %m "$dir"/* | sort -n | tail -1
1512428453

(This is close to BashFAQ 003, which is mostly about finding the file with the newest timestamp/largest size/etc., but contains some rather elaborate solutions.)

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.