Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

The stat command will give you the last modification time

stat -c %y <filename>

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

find file1 -maxdepth 0 -mmin -3

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top