-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile_sync.sh
More file actions
78 lines (65 loc) · 2.59 KB
/
file_sync.sh
File metadata and controls
78 lines (65 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/bin/bash
# Log file path
log_file="file_sync.log"
# Function to log messages
log_message() {
echo "$(date +"%Y-%m-%d %H:%M:%S"): $1" >> "$log_file"
}
# Function to copy new files by extension pattern
copy_new_files() {
source_dir="$1"
destination_dir="$2"
extension="$3"
# Check if source directory exists and is readable
if [ ! -d "$source_dir" ] || [ ! -r "$source_dir" ]; then
log_message "Source directory does not exist or is not readable: $source_dir"
return 1
fi
# Check if destination directory exists and is writable
if [ ! -d "$destination_dir" ] || [ ! -w "$destination_dir" ]; then
log_message "Destination directory does not exist or is not writable: $destination_dir"
return 1
fi
log_message "Start copying"
# Copy new files with the specified extension pattern
copied_files=0
skipped_files=0
for file in "$source_dir"/*."$extension"; do
filename=$(basename "$file")
destination_file="$destination_dir/$filename"
if [[ ! -f "$destination_file" ]]; then
cp "$file" "$destination_dir"
log_message "Copied: $filename"
((copied_files++))
else
source_file_size=$(stat -c%s "$file")
destination_file_size=$(stat -c%s "$destination_file")
source_file_date=$(stat -c%Y "$file")
destination_file_date=$(stat -c%Y "$destination_file")
if [[ $source_file_size -ne $destination_file_size ]] || [[ $source_file_date -gt $destination_file_date ]]; then
cp "$file" "$destination_dir"
log_message "Copied: $filename (size or date mismatch)"
((copied_files++))
else
log_message "Skipped: $filename (already exists in destination directory)"
((skipped_files++))
fi
fi
done
log_message "Copying complete"
log_message "Copied files: $copied_files"
log_message "Skipped files: $skipped_files"
return 0
}
# Check if all command-line arguments are provided
if [ $# -ne 3 ]; then
echo "Usage: ./script.sh <source_directory> <destination_directory> <extension_pattern>"
log_message "Wrong usage detected, please folow this as example './script.sh <source_directory> <destination_directory> <extension_pattern>'"
exit 1
fi
# Assign command-line arguments to variables
source_directory="$1"
destination_directory="$2"
extension_pattern="$3"
# Call the copy_new_files function with the provided variables
copy_new_files "$source_directory" "$destination_directory" "$extension_pattern"