Jas*_* M. 33 scripting bash rsync
我在 bash 脚本中使用 rsync 来保持几个服务器和 NAS 之间的文件同步。我遇到的一个问题是尝试生成在 rsync 期间已更改的文件列表。
这个想法是,当我运行 rsync 时,我可以将已更改的文件输出到文本文件中 - 更希望内存中有一个数组 - 然后在脚本存在之前,我可以只对已更改的文件运行 chown 。
有没有人找到一种方法来执行这样的任务?
# specify the source directory
source_directory=/Users/jason/Desktop/source
# specify the destination directory
# DO NOT ADD THE SAME DIRECTORY NAME AS RSYNC WILL CREATE IT FOR YOU
destination_directory=/Users/jason/Desktop/destination
# run the rsync command
rsync -avz $source_directory $destination_directory
# grab the changed items and save to an array or temp file?
# loop through and chown each changed file
for changed_item in "${changed_items[@]}"
do
# chown the file owner and notify the user
chown -R user:usergroup; echo '!! changed the user and group for:' $changed_item
done
Run Code Online (Sandbox Code Playgroud)
Kyl*_*ith 53
您可以使用 rsync 的--itemize-changes
( -i
) 选项生成如下所示的可解析输出:
~ $ rsync src/ dest/ -ai
.d..t.... ./
>f+++++++ newfile
>f..t.... oldfile
~ $ echo 'new stuff' > src/newfile
~ $ !rsync
rsync src/ dest/ -ai
>f.st.... newfile
Run Code Online (Sandbox Code Playgroud)
第>
一个位置的字符表示文件已更新,其余字符表示更新原因,例如此处s
并t
表示文件大小和时间戳已更改。
获取文件列表的一种快速而肮脏的方法可能是:
rsync -ai src/ dest/ | egrep '^>'
显然更高级的解析可以产生更清晰的输出:-)
我在尝试找出何时--itemize-changes
引入时遇到了这个很棒的链接,非常有用:
http://andreafrancia.it/2010/03/understanding-the-output-of-rsync-itemize-changes.html(存档链接)
JDS*_*JDS 19
使用-n
标志,结合-c
校验和标志和-i
标志:
# rsync -naic test/ test-clone/
>fcst...... a.txt
>fcst...... abcde.txt
>fcst...... b.txt
Run Code Online (Sandbox Code Playgroud)
在此示例中,根据文件本身的内容(由校验和确定),三个文件已更改。但是,由于-n
标志的原因,没有进行文件同步
奖金
如果要对更改的文件运行 chown,请使用sed
或类似的方法解析它们并使用 xargs 进行处理,例如:
rsync -naic test/ test-clone/ | sed 's/............//' | xargs -I+ sudo chown root "test-clone/+"
Run Code Online (Sandbox Code Playgroud)
小智 7
这个问题有点老了,但我认为值得补充:
-i
是捷径 --out-format=%i%n%L
和%n
装置的文件名,(部分log format
的man rsyncd.conf
)
PS rsync 版本 3.1.0