简体   繁体   中英

Bash: calculate age of the newest file in directory

I need a bash script to get the age of the newest file in given directory (in hours or seconds). For example:

-rw-r--r-- 1 root root 3.0M 2012-12-31 12:36 2012_12_31_1236_redis_dump_encrypted.tgz
-rw-r--r-- 1 root root 2.8M 2013-01-01 11:33 2013_01_01_1133_redis_dump_encrypted.tgz
-rw-r--r-- 1 root root 2.4M 2013-01-04 14:17 2013_01_04_1417_redis_dump_encrypted.tgz
-rw-r--r-- 1 root root 2.7M 2013-01-05 12:26 2013_01_05_1226_redis_dump_encrypted.tgz
-rw-r--r-- 1 root root  54M 2013-01-06 14:16 2013_01_06_1415_redis_dump_encrypted.tgz
-rw-r--r-- 1 root root 3.7M 2013-01-07 16:42 2013_01_07_1642_redis_dump_encrypted.tgz
-rw-r--r-- 1 root root 3.4M 2013-01-08 12:36 2013_01_08_1236_redis_dump_encrypted.tgz

Command should accept path to directory and return how many seconds have passed since newest file ( 2013_01_08_1236_redis_dump_encrypted.tgz ) was created.

I need this in order to monitor age of the latest backup with zabbix (I want an alert in case backup mechanism breaks). One-liner would be great, because it is more conviniant to use as zabbix user parameter, but not necessary.

Thank you!

Perl救援:

perl -le '$d=shift;chomp($f=(`ls -t $d/*`)[0]);print 24*60*60*-M$f' /path/to/dir

It's as old post but maybe it helps somebody.

I use the below method to calculate time in hours for files

 echo $(( ( $(date +%s) - $(stat -c %Y filen.name)) / (60*60)  ))

date +%s - gives seconds since 1970-01-01 00:00:00 UTC

stat -c %Y - gives the same for the file in the parameter

This doesn't work on OS X and BSD, stat doesn't have -c option but most Linux distributions should be ok.

This is probably a bit fragile but should return the age in seconds of the newest file (or directory) in $DIR :

echo $(( $(date +%s) - $(ls -t $DIR | head -1 | xargs stat -f %a -t %s) ))

The %s time format is the number of seconds since the epoch, so the above line gets the name of the newest file ( ls -t $DIR | head -1 ), gets its last accessed time time in seconds since the epoch ( stat -f %a -t %s ), and subtracts this from the current time in seconds since the epoch.

这将返回以秒为单位的年龄和文件名。

stat -c "%Y %n" -- * | sort -rn | awk -v d=$(date +%s) 'NR==1 {print (d-$1), $2; exit}'
# If no files less than 5 minutes old are found, print a 1. Otherwise print a 0.
if [[ -z $(find $PATH -type f -mmin -5 2>/dev/null) ]]; then echo "1"; else echo "0"; fi

This is pretty clean for a one-liner! The minute you need to send in command-line arguments, you need.. a PROGRAM! G0T0 10 FTW!!!!!1!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM