问题描述
我有以下bash脚本。在脚本中,我使用rsync将文件从源复制到目标。在rsync的第一个调用中,我复制了所有文件,在第二个调用中,我仔细检查了文件,如果校验和有效,则复制的文件在源中被删除。
#!/bin/bash
set -e
rsync --info=progress2 -r --include='database/session_*.db' --exclude 'database/session*' /local/data/ /import/myNas/data
rsync --info=progress2 -r --include='database/session_*.db' --exclude 'database/session*' --checksum --remove-source-files /local/data/ /import/myNas/data
现在的问题是,在rsync运行时,新文件被写入/local/data
。我希望rsync第一次运行时对其源(/local/data
)中的文件列表进行快照,然后仅复制这些文件。然后在第二次运行中rsync也应该仅对快照中的这些文件运行(即计算校验和,然后删除文件)。这意味着不应触摸新添加的文件。
这可能吗?
解决方法
在运行null
之前,先填充rsync
分隔的文件列表以进行同步:
#!/usr/bin/env bash
##### Settings #####
# Location of the source data files
declare -r SRC='/local/data/'
# Destination of the data files
declare -r DEST='/import/myNas/data/'
##### End of Settings #####
set -o errexit # same as set -e,exit if command fail
declare -- _temp_fileslist
trap 'rm -f "$_temp_fileslist"' EXIT
_temp_fileslist=$(mktemp) && typeset -r _temp_fileslist
# Populate files list as null delimited entries
find "$SRC" \
-path '*/database/session_*.db' \
-and -not -path '*/database/session*' \
-fprinf "$_temp_fileslist" '%P\0'
# --from0 tells rsync to read a null delimited list
# --files-from= tells to read the include list from this file
if rsync --info=progress2 --recursive \
--from0 "--files-from=$_temp_fileslist" -- "$SRC" "$DEST";
then rsync --info=progress2 --recursive \
--from0 "--files-from=$_temp_fileslist" \
--checksum --remove-source-files -- "$SRC" "$DEST"
fi