Script: Put Fotos into Year and Month Subfolder

Hi all,

with my android phone I used the nextcloud app to sync my fotos. This app had a cool feature to create subfolders for year and month to better organize my fotos.

While I am with my librem 5 using the nextcloud desktop client the folder functionality was not yet there.

That’s why I scripted it myself. The script only moves files to folders depending on it’s creation date and only works until the year 9999.

#!/bin/bash

# Where your fotos are - in this case in the Pictures folder - standard of the foto app
PIC=/home/purism/Pictures

# Where all Fotos should go to - e.g. to an external sdcard
target=/media/nextcloud/fotos

cd "$PIC"

for file in *; do
    # Top tear folder name
    date=$(stat -c '%w' "$file") 
    year=${date:0:4}
    month=${date:5:2}
    echo "$file - $year - $month"

    if [ ! -d "$target/$year" ]; then
        mkdir "$target/$year"
        echo "starting new year: $year"
    fi
    if [ ! -d "$target/$year/$month" ]; then
        mkdir "$target/$year/$month"
        echo "starting new month in year $year: $month"
    fi
    echo "moving $file"
    mv "$file" "$target/$year/$month/$file"
    # if you like to keep the old link e.g. for the camera app
    ln -s "$target/$year/$month/$file" "$file"
done

The only thing you now could do is either let your camera app trigger this script or make a simple cronjob to execute this script regularly or maybe when you join a cetain wifi. Feel free to also share in case you use it.
Sure - this script will be obsolete once the camera app let’s you chose other locations, subfolders, name shemes etc.

Have fun!

Max

9 Likes

Sometimes the file creation date doesn’t give the accurate date for the picture — especially after the file has been copied, since cp, by default, destroys creation date. Almost all JPG pictures have a date field in the EXIF metadata for the picture. There are lots of command line tools to extract that (e.g. exif, exiftool, exif2, and even something like imagemagick’s "identify -verbose | grep “exif:” | grep “DateTimeOriginal” ).