Wade Jensen Wade Jensen - 18 days ago 5
Linux Question

Check last modified date is within n seconds

I need to check the last modified date of all files within a directory to see if the latest file has been modified within some arbitrary period. Eg. 200 seconds.

Here's the twist, it also has to be a one-liner (its a Marathon health check and I can't rely on a file system being there for a script file).

Here's what I have so far:

ls -v | tail -n 1 | expr $(date +%s) - $(xargs date +%s -r) | if [ $PREV -gt 100 ]; then echo 1; else echo 0; fi

The ls -v sorts directory contents in "natural order" (the file names are monotonically increasing), so the latest file will be always be the last.
tail -n 1 gets the last value.

Then expr $(date +%s) - $(xargs date +%s -r) subtracts the file's last modified date from now as a unix timestamp.

Next I want to pass the result forward to an if statement and return 0 or 1 depending on comparison with a constant. But I can't work out how to get the pipe output into the if statement.

Note: I'm aware I could have the if check in the previous pipe wrapping the subtraction, but I think that the one-liner is already confusing enough as it is.

Any help appreciated.
Host OS is Linux. Bash shell.


This code works.

if [ `expr $(date +%s) - $(stat -c %Y $(ls -t | head -n 1))` -gt 100 ];then echo 1;else echo 0;fi

How does it work?

ls -t - lists the files based on the time.

head -n 1 - gives first latest file.

date +%s gives time elapsed since epoch.

stat -c %Y - gives modification time since epoch

expr - subtracting present date from modified file date.