Skip to content

Instantly share code, notes, and snippets.

@jonblack
Last active August 5, 2024 09:49
Show Gist options
  • Save jonblack/9e907739527a56877212362e2844e5db to your computer and use it in GitHub Desktop.
Save jonblack/9e907739527a56877212362e2844e5db to your computer and use it in GitHub Desktop.
photo_org
#!/usr/bin/env sh
phone_photos="$1"
photos_root="$2"
for filename in "$phone_photos"/**/*; do
# Some paths can be ignored. For now lets hard code them.
case "$filename" in
*.thumbnail*) continue ;; # thumbnails
*.stfolder*) continue ;; # syncthing folder marker
esac
# Get the creation date from the media format meta data. If not found, use
# the file modified time.
c_date=$(exiftool "$filename" -CreateDate -d "%Y-%m" | cut -d : -f 2 | tr -d '[:space:]')
c_fdt=$(exiftool "$filename" -CreateDate -d "%Y%m%d%H%M%S" | cut -d : -f 2 | tr -d '[:space:]')
if [ "$c_date" = "0000" ] || [ "$c_date" = "" ]; then
# The arguments for stat are specific to freenas and are not very
# portable. This could break at any time. (exiftool has FileModifyDate, try
# that some time.
c_date=$(stat -f %Sm -t %Y-%m "$filename")
c_fdt=$(stat -f %Sm -t %Y%m%d%H%M%S "$filename")
fi
# Only continue if there wasn't an error
if [ $? -eq 0 ]; then
c_date_y=$(echo "$c_date" | cut -d - -f 1)
c_date_m=$(echo "$c_date" | cut -d - -f 2)
if [ ! -d "$photos_root/$c_date_y/$c_date_m" ]; then
mkdir -p "$photos_root/$c_date_y/$c_date_m"
fi
# Add date/time to new filename to make files as unique as possible.
# Cameras are rubbish at filenaming, and duplicates are possible when
# multiple cameras are used.
filename_base=$(basename "$filename")
filename_raw="${filename_base%.*}"
filename_ext="${filename_base##*.}"
new_filename="$filename_raw"_"$c_fdt"."$filename_ext"
new_path="$photos_root/$c_date_y/$c_date_m/$new_filename"
if [ ! -f "$new_path" ]; then
echo cp "$filename" "$photos_root/$c_date_y/$c_date_m/$new_filename"
cp "$filename" "$photos_root/$c_date_y/$c_date_m/$new_filename"
fi
else
echo "Failed to process $filename"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment