Setting file date and time to date/time of oldest file in current folder (Linux only)

Roon allows you to order albums by modification date/time which is pretty handy if you like to see new additions first in your album view.

A while ago I ran a tool across a portion of my library and forgot to preserve the last modified date/time. Luckily the tool only made changes to audio files so I could use other unaffected files in each folder to reinstate the last modified date/time to that of the oldest file in each folder, which would represent the day I had tagged and filed that album (my workflow has always included running touch across content before filing).

In any event, I needed a way to automate the update, so here it is:

#!/bin/bash

touch_dir() {
          cd "$1"
          # uncomment if you want to use file date and timestamps only
          oldest_file="$(find "$PWD" -mindepth 1 -maxdepth 1 -type f -printf '%T+ %p\n' | sort | head -1| cut -d' ' -f2-)"
          # uncomment if you want to use file and/or folder date and timestamps
          #oldest_file="$(find "$PWD" -mindepth 1 -maxdepth 1 -printf '%T+ %p\n' | sort | head -1 | cut -d' ' -f2-)"

if [ -n "$oldest_file" ]

then

      echo "Processing "$PWD""
      # set date and timestamp of all files and parent folder using reference file
      find "$PWD" -mindepth 1 -maxdepth 1 -type f -print0 | xargs -I {} -0 touch -m -r "$oldest_file" "{}"
      touch -m -r "$oldest_file" "$PWD"

fi
}

export -f touch_dir
find "$PWD" -type d \( ! -name . \) -execdir bash -c 'touch_dir "$0"' {} \;

The script will walk an entire directory tree, processing each sub-directory independently, starting with the directory in which you run it.

As always, posted so I have something to come back to. Use at your own risk.