Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use shell script checking last changed time of a file

I want to find if certain files are changed within the last three minutes in order to decide if the cp was successful, and if I should exit or continue the script. How can I do that?

Thanks

like image 984
derrdji Avatar asked Jul 30 '09 14:07

derrdji


3 Answers

The syntax of this if statement depends on your particular shell, but the date commands don't. I use bash; modify as necessary.

if [ $(( $(date +%s) - $(date +%s -r <file>) )) -le 180 ]; then
    # was modified in last three minutes
else
    # was not modified in last three minutes
fi

The +%s tells date to output a UNIX time (the important bit is that it's an integer in seconds). You can also use stat to get this information - the command stat -c %Y <file> is equivalent. Make sure to use %Y not %y, so that you get a usable time in seconds.

like image 70
Cascabel Avatar answered Oct 20 '22 01:10

Cascabel


Find can output the file name if it has been modified in the last 3 minutes.

find file1 -maxdepth 0 -mmin -3
like image 38
Steve Zobell Avatar answered Oct 20 '22 00:10

Steve Zobell


You can get the last modification time of a file with stat, and the current date with date. You can use format strings for both to get them in "seconds since the epoch":

current=`date +%s`
last_modified=`stat -c "%Y" $file`

Then, it's pretty easy to put that in a condition. For example:

if [ $(($current-$last_modified)) -gt 180 ]; then 
     echo "old"; 
else 
     echo "new"; 
fi
like image 33
tsg Avatar answered Oct 20 '22 00:10

tsg