开发者

Bash script — determine if file modified?

I have a Bash script that repeatedly copies files every 5 seconds. But this is a t开发者_如何学运维ouch overkill as usually there is no change.

I know about the Linux command watch but as this script will be used on OS X computers (which don’t have watch, and I don’t want to make everyone install macports) I need to be able to check if a file is modified or not with straight Bash code.

Should I be checking the file modified time? How can I do that?

Edit: I was hoping to expand my script to do more than just copy the file, if it detected a change. So is there a pure-bash way to do this?


I tend to agree with the rsync answer if you have big trees of files to manage, but you can use the -u (--update) flag to cp to copy the file(s) over only if the source is newer than the destination.

cp -u

Edit

Since you've updated the question to indicate that you'd like to take some additional actions, you'll want to use the -nt check in the [ (test) builtin command:

#!/bin/bash

if [ $1 -nt $2 ]; then
  echo "File 1 is newer than file 2"
else
  echo "File 1 is older than file 2"
fi

From the man page:

file1 -nt file2
         True if file1 is newer (according  to  modification  date)  than
         file2, or if file1 exists and file2 does not.

Hope that helps.


OS X has the stat command. Something like this should give you the modification time of a file:

stat -f '%m' filename

The GNU equivalent would be:

stat --printf '%Y\n' filename


You might find it more reliable to detect changes in the file content by comparing the file size (if the sizes differ, the content does) and the hash of the contents. It probably doesn't matter much which hash you use for this purpose: SHA1 or even MD5 is probably adequate, and you might find that the cksum command is sufficient.

File modification times can change without changing the content (think touch file); file modification times can not change even when the content does (doing this is harder, but you could use touch -r ref-file file to set the modification times of file to match ref-file after editing the file).


No. You should be using rsync or one of its frontends to copy the files, since it will detect if the files are different and only copy them if they are.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜