提问人:BPippadi 提问时间:10/13/2023 更新时间:10/13/2023 访问量:34
Linux 中从源到目标 nas 路径的文件同步未按预期工作
File sync from source to target nas path in linux not working as expected
问:
我们在 linux 机器上没有可用的 rsync 或 xcopy,下面是我们建议的解决方案,有没有更好的方法来实现从源到目标的文件同步
替代建议会有所帮助
#!/bin/bash
# Check for correct number of arguments
if [[ $# -ne 2 ]]; then
echo "Usage: $0 <source_directory> <user@remote:target_directory>"
exit 1
fi
# Define the source and target directories from script arguments
SOURCE_DIR="$1"
TARGET_DIR="$2"
# Create a temporary directory for the file lists
TEMP_DIR=$(mktemp -d)
# Create a list of files and directories in the source directory
find "$SOURCE_DIR" -type f > "$TEMP_DIR/source_files.txt"
find "$SOURCE_DIR" -type d > "$TEMP_DIR/source_dirs.txt"
# Create a list of files and directories in the target directory
ssh "${TARGET_DIR%%:*}" "find '${TARGET_DIR##*:}' -type f" > "$TEMP_DIR/target_files.txt"
ssh "${TARGET_DIR%%:*}" "find '${TARGET_DIR##*:}' -type d" > "$TEMP_DIR/target_dirs.txt"
# Sync directories
while IFS= read -r dir
do
relative_dir="${dir#$SOURCE_DIR}"
if ! grep -qF "$relative_dir" "$TEMP_DIR/target_dirs.txt"; then
ssh "${TARGET_DIR%%:*}" "mkdir -p '${TARGET_DIR##*:}$relative_dir'"
fi
done < "$TEMP_DIR/source_dirs.txt"
# Sync files
while IFS= read -r file
do
relative_file="${file#$SOURCE_DIR}"
if ! grep -qF "$relative_file" "$TEMP_DIR/target_files.txt"; then
scp "$file" "${TARGET_DIR}$relative_file"
else
source_info=$(stat -c "%Y %s" "$file")
target_info=$(ssh "${TARGET_DIR%%:*}" "stat -c '%Y %s' '${TARGET_DIR##*:}$relative_file'")
if [[ $source_info != $target_info ]]; then
scp "$file" "${TARGET_DIR}$relative_file"
fi
fi
done < "$TEMP_DIR/source_files.txt"
# Clean up
rm -rf "$TEMP_DIR"
尝试了多个自定义脚本
答: 暂无答案
评论