MacOS – How to set Last Modified Date of file after using HandbrakeCLI to convert a file

bashcommand linefile conversionmacos

Running this on OS X Lion.

I'm batch converting several hundred home movies using Handbrake CLI. I'd like to set the last modified date and created date to that original file.

I'm using the following script:

for f in "$@"; do
  base=${f%.*}
  extension=${f##*.}
  newfile=${base}.m4v
  echo Converting \"$f\" to \"$newfile\"
  /Applications/HandBrakeCLI  -e x264 -b 4000 -a 1 -E faac -B 160 -R 48 -6 dpl2 -f mp4 --crop 0:0:0:0  -x level=40:ref=2:mixed-refs:bframes=3:weightb:subme=9:direct=auto:b-pyramid:me=umh:analyse=all:no-fast-pskip:filter=-2,-1 -i "$f" -o "$newfile"    
done

I execute this script by running:

find . -name "*.avi" -print0 | xargs -0 hbapple.sh

Does anyone have thoughts on how I can set the last modified and creation time of the original file to that of the $newfile?

If I don't figure out how to do this I will have a difficult time knowing when these videos were actually created.

I appreciate any help or pointers

Best Answer

The modification date can be set with

touch -m -t 201207010742 whatever.m4v

AFAIK the creation/birth date can't be modified.

To set the modification date based on the creation date of another file you can use stat:

touch -m -t $(stat -f %SB -t %Y%m%d%H%M original-file.mov) new-file-m4v

To apply this to your script, use something like

for f in "$@"
  do
     olddate=$(stat -f %SB -t %Y%m%d%H%M "$f")
     base=${f%.*}
     extension=${f##*.}
     newfile=${base}.m4v
     echo Converting \"$f\" to \"$newfile\"
     /Applications/HandBrakeCLI  -e x264 -b 4000 -a 1 -E faac -B 160 -R 48 -6 dpl2 -f mp4 --crop 0:0:0:0  -x level=40:ref=2:mixed-refs:bframes=3:weightb:subme=9:direct=auto:b-pyramid:me=umh:analyse=all:no-fast-pskip:filter=-2,-1 -i "$f" -o "$newfile"
     touch -m -t $olddate "$newfile"    
  done