script to correct the modification dates on files

It's been discovered that Dropbox bases its file dates on exif data in images, which is bad, because the image exif data is sometimes written by old-style point-n-shoot cameras which may or may not have had their date/time clock set correctly. In my case, I'm too lazy to bother as the UI on those old cameras is awful. Why use an old camera? well the latest polaroid cameras behave like that.

Anyway.

This script fixes the exif date as well as the file create, modify and open dates.

#!/bin/bash
# Check if both date and filename are provided
if [ -z "$1" ] || [ -z "$2" ]; then
  echo "Usage: $0 <date: yyyyMMdd or yyyy-MM-dd> <filename>"
  exit 1
fi
# Extract and clean inputs
DATE=$(echo "$1" | tr -d '[:space:]')  # Trim any spaces
FILENAME="$2"
# Debug: Display received inputs
echo "DEBUG: Received date: '$DATE', Filename: '$FILENAME'"
# Check if the date is in a valid format (YYYYMMDD or YYYY-MM-DD)
if [[ ! "$DATE" =~ ^[0-9]{8}$ ]] && [[ ! "$DATE" =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then
  echo "Error: Date must be in yyyyMMdd or yyyy-MM-dd format."
  exit 1
fi
# Convert date to YYYY-MM-DD format if needed
if [[ "$DATE" =~ ^[0-9]{8}$ ]]; then
  DATE_FORMATTED="${DATE:0:4}-${DATE:4:2}-${DATE:6:2}"  # Convert YYYYMMDD to YYYY-MM-DD
else
  DATE_FORMATTED="$DATE"
fi
# Convert to MM/DD/YYYY for SetFile
DATE_SETFILE="${DATE_FORMATTED:5:2}/${DATE_FORMATTED:8:2}/${DATE_FORMATTED:0:4}"
# Debug: Display formatted date
echo "DEBUG: Formatted date: '$DATE_FORMATTED', SetFile date: '$DATE_SETFILE'"
# Check if the file is an image (case-insensitive)
if [[ ! "$FILENAME" =~ \.(jpg|jpeg|png|gif|tif|tiff|JPG|JPEG|PNG|GIF|TIF|TIFF)$ ]]; then
  echo "Error: $FILENAME is not a supported image file."
  exit 1
fi
# Construct date strings
CREATION_DATE="$DATE_SETFILE 12:00:00"
MOD_ACCESS_DATE="${DATE_FORMATTED//-/}1200"  # Remove hyphens for touch command format
# Debug: Display date strings
echo "DEBUG: Creation date: '$CREATION_DATE', Touch date: '$MOD_ACCESS_DATE'"
# Step 1: Update EXIF metadata with ExifTool
exiftool '-DateTimeOriginal<FileModifyDate' '-CreateDate<FileModifyDate' '-ModifyDate<FileModifyDate' "$FILENAME" -overwrite_original
# Step 2: Set the filesystem dates after ExifTool
echo "DEBUG: Running SetFile -d '$CREATION_DATE' '$FILENAME'"
SetFile -d "$CREATION_DATE" "$FILENAME" && \
touch -mt "$MOD_ACCESS_DATE" "$FILENAME" && \
touch -at "$MOD_ACCESS_DATE" "$FILENAME"
echo "Dates updated for $FILENAME to $DATE_FORMATTED and EXIF metadata synced to FileModifyDate"

Popular posts from this blog

The most useful defaults-write options

Erasing firmware password

Migrating from Windows to Mac