
我有兩個目錄,我需要僅同步目標目錄中已存在的子目錄的內容。例如:
原始碼目錄:
- 資料夾A
- 資料夾B
- 資料夾C
- 資料夾D
- 資料夾E
目標目錄:
- 資料夾B
- 資料夾D
- 資料夾Z
我需要將資料夾 B 和資料夾 D 的唯一內容從來源同步到目標(並且資料夾 Z 在來源中不存在,因此應被忽略)。同樣,我不需要目標目錄來將資料夾 A、C 和 E 複製到其中。
本質上是「對於目標中的所有子目錄,如果來源中存在相同的子目錄,則從來源中同步該子目錄的內容」。
如果有幫助的話,這些都是本地目錄。
希望這是有道理的。感謝您的幫忙!
答案1
您可以使用這樣的腳本。
(
cd destination &&
for d in *
do
[ -d "$d" -a -d source/"$d" ] && rsync -a source/"$d" .
done
)
如果它是獨立的,則不需要括號,( ... )
因為它們僅用於本地化目錄變更。
如果您希望目標中的檔案在來源中不再存在時將其刪除,請新增--delete
至。rsync
答案2
建立以下bash
腳本,更改來源目錄和目標目錄的路徑並執行它。
#!/bin/bash
source=/path_to/source_dir
destination=/path_to/destination_dir
shopt -s nullglob
{
for dir in "$destination/"*/; do
dirname=$(basename "$dir")
if [ -d "$source/$dirname" ]; then
printf '+ /%s/***\n' "$dirname"
fi
done
printf -- '- *\n'
} > "$source/filter.rules"
#rsync -av --filter="merge $source/filter.rules" "$source"/ "$destination"
filter.rules
這將在來源目錄中建立一個包含以下內容的檔案:
+ /folder B/***
+ /folder D/***
- *
第一行+ /folder B/***
是簡短的語法
+ /folder B/
包括目錄+ /folder B/**
包含檔案和子目錄
並- *
排除根目錄中的檔案和目錄。
如果規則看起來符合預期,請取消註解最後一行並rsync
使用合併篩選器再次執行腳本到目錄。
答案3
旗幟--existing
就是您要尋找的。從手冊頁:
--existing, --ignore-non-existing
This tells rsync to skip creating files (including
directories) that do not exist yet on the destination. If this option is combined
with the --ignore-existing option, no files will be updated (which can be useful
if all you want to do is delete extraneous files).
This option is a transfer rule, not an exclude, so it doesn’t affect the data that
goes into the file-lists, and thus it doesn’t affect deletions. It just limits
the files that the receiver requests to be transferred.