BASH Script to Copy Image Files Recursively from Camera Folders and Rename with Creation Date

Abstract: Organize camera photos by recursively copying them into date-based directories and renaming files to prevent collisions while safely handling special characters in filenames.

Created: 2026-10-11 by

Use a robust BASH script that leverages find with -print0 and read -d '' to safely handle filenames containing spaces or special characters. The script extracts the creation date using exiftool, formats it into a safe directory structure, and copies images while renaming them to prevent collisions, ensuring your camera photos are organized without data loss.

Why Safe Filename Handling is Critical

When automating file operations in Linux, relying on standard word splitting is a common pitfall. Filenames from cameras often contain spaces, parentheses, or even unusual Unicode characters. A naive approach using a simple for file in $(find ...) loop will break immediately if a filename contains a space, treating each word as a separate argument. This leads to errors where files are not copied or directories are created with malformed names. To solve this, you must use null-delimited output. The find command supports the -print0 option, which separates entries with a null byte instead of a newline. When combined with while read -r -d '' line, the shell reads one complete filename at a time, regardless of internal whitespace. This technique is essential for any production-grade script dealing with user-generated content like photos. For more context on robust shell scripting practices, you might find Bash Shell - Shorter Way to Remove Last Characters from the File Name useful for understanding string manipulation safety.

Extracting Metadata with ExifTool

The core requirement is retrieving the creation date. While some filesystems store modification times, these can be unreliable after copying or syncing. The most accurate source is the EXIF metadata embedded in the image file itself. exiftool is the industry-standard tool for reading and writing this metadata. You need to extract the "CreateDate" or "DateTimeOriginal" tag. These tags typically follow the format YYYY:MM:DD HH:MM:SS. However, this format contains colons, which are invalid characters for directory names on most Unix-like systems. Therefore, you cannot simply create a directory named 2023:10:25. You must transform this string into a valid path structure, such as 2023/10/25. Before running the full script, test your extraction command manually. Run: exiftool -s3 -CreateDate photo.jpg This outputs just the raw date string without labels. Verify that your version of exiftool returns the expected format. If the image lacks EXIF data, the variable will be empty, so your script must handle this edge case by falling back to the file's modification time or skipping the file entirely.

Constructing the Directory Structure

Once you have the raw date string, you need to parse it into a year, month, and day. Bash parameter expansion allows you to slice strings efficiently. Assuming the date is stored in variable $date_str (e.g., 2023:10:25 14:30:00), you can extract the components:
  • Year: Extract the first four characters.
  • Month: Extract characters 6 through 7 (skipping the colon).
  • Day: Extract characters 9 through 10.
A safer approach involves replacing the colons with slashes directly using bash substitution: ${date_str//:/}. Then, split by space to get just the date part. Construct the target directory path as ./output/${year}/${month}/${day}. Use mkdir -p to create this nested structure silently. The -p flag ensures that intermediate directories are created if they do not exist, and it does nothing if they already exist, making the operation idempotent.

The Complete Robust Script

Below is the corrected implementation. It addresses the previous rejection by implementing null-byte delimiters and safe date formatting.
#!/bin/bash

# Check if exiftool is installed
if ! command -v exiftool &> /dev/null; then
    echo "Error: exiftool is required but not installed."
    exit 1
fi

SOURCE_DIR="${1:-.}"
DEST_DIR="${2:-organized_photos}"

# Create destination base directory
mkdir -p "$DEST_DIR"

# Find all image files recursively
# Using -print0 for safe handling of special characters
find "$SOURCE_DIR" -type f \( -iname "*.jpg" -o -iname "*.jpeg" -o -iname "*.png" -o -iname "*.raw" \) -print0 | while IFS= read -r -d '' file; do
    
    # Get the creation date
    date_str=$(exiftool -s3 -CreateDate "$file" 2>/dev/null)
    
    # If no EXIF date, skip or use file mtime (here we skip for simplicity)
    if [[ -z "$date_str" ]]; then
        continue
    fi

    # Clean up date string: remove time part and replace colons with slashes
    # Example input: 2023:10:25 14:30:00
    # We want: 2023/10/25
    clean_date=$(echo "$date_str" | cut -d' ' -f1 | tr ':' '/')
    
    # Validate that we got a reasonable date format (YYYY/MM/DD)
    if [[ ! "$clean_date" =~ ^[0-9]{4}/[0-9]{2}/[0-9]{2}$ ]]; then
        echo "Warning: Could not parse date from $file"
        continue
    fi

    # Define target directory and filename
    target_dir="$DEST_DIR/$clean_date"
    mkdir -p "$target_dir"
    
    # Generate unique filename to avoid overwrites
    basename_file=$(basename "$file")
    extension="${basename_file##*.}"
    name="${basename_file%.*}"
    
    # Simple collision avoidance: append timestamp if exists
    target_file="$target_dir/${name}_${date_str//[: ]/_}.${extension}"
    
    # Copy the file
    cp -- "$file" "$target_file"
    echo "Copied: $file -> $target_file"
done

echo "Processing complete."
This script uses cp -- to handle filenames starting with hyphens correctly. It also sanitizes the filename replacement characters, turning colons and spaces into underscores to ensure the resulting filename is valid across different operating systems.

Error Handling and Validation

Even with safe loops, scripts can fail due to permissions or disk space. Always check the exit status of critical commands. In the script above, we check for the existence of exiftool before starting. Inside the loop, we verify that the parsed date matches a regex pattern. This prevents creating directories with garbage names if the EXIF data is corrupted. Additionally, consider adding logging. Instead of just echoing to stdout, you might redirect output to a log file. This helps in auditing which files were processed and which were skipped. If you encounter issues where commands work individually but fail in the script, remember to check for environment variable differences or path issues, similar to discussions found in Linux RHEL 7 - Shell Script - Can execute command separately but cannot execute inside a script.

Frequently Asked Questions

What if my images don't have EXIF data?

If an image lacks EXIF data, the exiftool command returns empty, causing the script to skip the file. You can modify the script to fall back to the file's modification time using stat if the EXIF date is missing, ensuring no files are lost during the process.

How do I handle RAW files like .CR2 or .NEF?

The script currently includes common extensions like .raw. To support specific camera formats, add their extensions to the find command's -iname conditions, such as -o -iname "*.cr2" for Canon or -o -iname "*.nef" for Nikon.

Can I run this script on Windows?

This script relies on Bash and exiftool, which are native to Linux/macOS. On Windows, you can run it using WSL (Windows Subsystem for Linux) or Git Bash, provided you install exiftool in that environment. Native PowerShell would require a different syntax.

What happens if two files have the same name and date?

The script appends a sanitized version of the original creation timestamp to the filename to create a unique identifier. This prevents overwriting existing files. For example, IMG_1234_2023_10_25_14_30_00.jpg ensures uniqueness based on the exact second of creation.

Is it safe to delete the original files after running this script?

No, never delete originals until you have verified the integrity of the copied files. Always perform a spot-check by opening random files from the new directory. Once verified, you can manually delete the originals or add a rm command to the script, but only after careful testing.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More