views:

575

answers:

4

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

A: 

The stat command will give you the last modification time

stat -c %y <filename>
Glen
A: 

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.

Jefromi
+2  A: 

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
tsg
A: 

A file timestamp change does not really imply you successfully copied.
If you land up corrupting the file or the file-system runs out of space,
you will probably still see a timestamp change (need to confirm that).

I do not get the exact context of your requirement.
If you fire a cp, it completes and returns -- does not return while it is working.
So, isn't the return (with success exit code) a good indicator of success?

How and why would you exit partly within a cp operation?
Or, is that a batch cp script that loops over the list of files...
some elaboration would help.

nik
the cp is done in one script and the verifying is done in another script. so exist will not stop cp in the middle. by the way, how can I get the verify the exist code of cp? thank you
derrdji
*get AND verify
derrdji