Last active
September 25, 2023 16:59
-
-
Save subhacom/4cc1aa5df6aae0ec831f to your computer and use it in GitHub Desktop.
rsync and md5sum: Use rsync to copy a directory and then generate a file containing the md5sum of all the files in source directory. Finally do a check of the md5sum of the target.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
if [ $# -lt 2 ]; then | |
echo "Usage: $0 source dest [md5file]" | |
echo "Copy source directory into dest directory and put md5 sum of the files in source in md5file. " | |
echo "If no md5 file is unspecified it is created in current directory" | |
echo | |
exit 0 | |
fi | |
source=$1 | |
target=$2 | |
if [ $# -gt 2 ]; then | |
md5file=$3 | |
else | |
md5file="`pwd`/`basename \"$source\"`.md5" | |
fi | |
# Remove trailing slash - we don't want that behavior of rsync | |
end=$((${#source}-1)) | |
echo "END $end" | |
echo "${source:$end:1}" | |
if [ "${source:$end:1}" = / ]; then | |
source="${source:0:$end}" | |
fi | |
echo "Copying ${source} to ${target}" | |
rsync -avz --chmod=ugo=rwX "${source}" "${target}" | |
pushd "$source" | |
# add the copied dirname to target path | |
tmp=$(basename "$source") | |
target="$target/$tmp" | |
index=0 | |
tmp=$md5file | |
while [ -f "$tmp" ]; do | |
echo "File $tmp already exists." | |
tmp="$md5file.$index" | |
index=$[$index+1] | |
done | |
# This solves problem with spaces in dir name: | |
# http://stackoverflow.com/questions/7194192/basename-with-spaces-in-a-bash-script | |
fbase=$(basename "$tmp") | |
echo "Basename of md5file: $fbase" | |
# In case the md5filename has no directory part specified put it in | |
# target directory | |
if [ "$fbase" = "$tmp" ]; then | |
tmp="$target/$tmp" | |
echo "Md5target: $tmp" | |
else | |
echo "Md5target1: $tmp" | |
fi | |
echo "Calculating md5sum and saving in $tmp." | |
find . -type f -exec md5sum {} \; > "$tmp" | |
if [ "${tmp:0:1}" = / ]; then | |
md5file="$tmp" | |
else | |
md5file=$(pwd)/$tmp | |
fi | |
echo "Original $tmp, realpath $md5file" | |
# if [[ "${source:$end:1}" != / ]]; then | |
echo "Target dir $target" | |
# fi | |
popd | |
echo "Dumped md5sum in $tmp" | |
pushd "$target" | |
echo "Checking md5sum for copied files: $md5file" | |
md5sum -c "$md5file" | |
cp "$md5file" ./ | |
popd | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment