Last active
January 13, 2021 04:18
-
-
Save stephan-t/dea9b35a0ce73d2a981e6b7fdf8ceaba to your computer and use it in GitHub Desktop.
Check integrity of files after being copied and report results
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 | |
# Check integrity of files after being copied and report results. | |
set -e | |
print_usage() { | |
echo "Usage: $(basename $0) [options] <filename> <destination path>" | |
echo "Options:" | |
echo " -r <size MB> generate and use random data file of specified size (MB)" | |
echo " -l <count> loop process a specified number of times" | |
echo " -v verbose output" | |
} | |
print_results() { | |
echo "Passed: $pass" | |
echo "Failed: $fail" | |
} | |
# Parse options | |
rand_file=0 | |
loop_count=1 | |
verbose=0 | |
while getopts r:l:v opt; do | |
case $opt in | |
r) | |
rand_file=1 | |
rand_file_size=$OPTARG | |
;; | |
l) | |
loop_count=$OPTARG | |
;; | |
v) | |
verbose=1 | |
;; | |
?) | |
print_usage | |
exit 2 | |
;; | |
esac | |
done | |
shift $((OPTIND - 1)) | |
# Check for arguments | |
filename=$1 | |
dest_path=$2 | |
if [ -z "$filename" ] || [ -z "$dest_path" ]; then | |
print_usage | |
exit 1 | |
fi | |
# Verify destination path | |
if [ ! -d "$dest_path" ]; then | |
echo "Destination path does not exist" | |
exit 1 | |
fi | |
pass=0 | |
fail=0 | |
for ((i = 1; i <= $loop_count; i++)); do | |
# Generate random file | |
if [ "$rand_file" -eq 1 ]; then | |
if [ "$verbose" -eq 1 ]; then | |
echo -e "Generating random file of size "$rand_file_size"MB...\n" | |
fi | |
dd if=/dev/random of="$filename" bs=1M count="$rand_file_size" 2> /dev/null | |
fi | |
# Copy source file to destination path | |
if [ "$verbose" -eq 1 ]; then | |
echo -e "Copying source file to destination path...\n" | |
fi | |
cp "$filename" "$dest_path" | |
# Calculate hashes | |
if [ "$verbose" -eq 1 ]; then | |
echo -e "Calculating hashes...\n" | |
fi | |
src_hash=$(md5sum $filename | awk '{print $1}') | |
dest_hash=$(md5sum $dest_path/$filename | awk '{print $1}') | |
if [ "$verbose" -eq 1 ]; then | |
echo "$src_hash (source)" | |
echo -e "$dest_hash (destination)\n" | |
fi | |
# Count hashes that pass or fail | |
if [ "$src_hash" = "$dest_hash" ]; then | |
((++pass)) | |
else | |
((++fail)) | |
fi | |
# Print results occasionally | |
if [ "$verbose" -eq 1 ] && [ $(($i % 5)) -eq 0 ] && [ "$i" -ne "$loop_count" ]; then | |
print_results | |
echo | |
fi | |
done | |
print_results |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment