1

I am using SUSE Linux Enterprise Server 11 (x86_64)
I need to find a folders oldest file and print it out in unixtime. I did get the job done with this one liner:
find $1 -maxdepth 1 -type f | xargs -i stat -c "%Y" '{}' | sort | head -n 1
(the $1 is for Zabbix)

But when the folder becomes empty the value also seem to be empty and my monitoring software, Zabbix, cant handle empty values so I need it to, for example print out number 0 if the folder is empty.

Okay so next I composed this beautiful script but as you all can see it's pretty shait. So could anyone help me out with this?
FYI. I started messing around with linux two days ago so please bear with me :P

#!/bin/bash    
export fileage
fileage=$(find -maxdepth 1 -type f | xargs -i stat -c "%Y" '{}' | sort | head -n 1)
if [ $? -eq 0 ]
then
   echo "0"  
else
   echo "fileage"
fi
jcbermu
  • 17,822
knob
  • 13

1 Answers1

2

find can print any of the 3 timestamps a file/directory can have. You just have to use -printf with the appropriate format sequence: %C@ or %A@ or %T@ (see the detail is man find).

As for empty directories, checking if $? is 0 can be misleading because 0 return code means "nothing bad has happened", and an empty directory does not count "something bad", it's just a special but normal case. But you can store the OUTPUT of find (and the following commands in the pipe) and check if it is empty or not.

Like

fileage=$(find $1 -maxdepth 1 -type f -printf "%T@\n" | sort | head -n 1)
if [ -z "fileage" ]; then
  echo 0
else
  echo $fileage
fi

or, if you like to be short:

fileage=$(find $1 -maxdepth 1 -type f -printf "%T@\n" | sort | head -n 1)
echo ${fileage:=0}

Nevertheless, be careful if you really want to see "oldest file" because that would mean reading the creation time of the file and that is not stored. You could have the oldest file with the newest of all the three timestamps.

user556625
  • 4,400