1

I have been trying without success to transfer the creation date from one file to another on OS X 10.8 (Mountain Lion) using Bash. It’s probably some combination of stat and touch but I haven’t quite figured it out, because the format used by stat does not match that needed by touch.

This is what I tried so far. It’s part of a video conversion script which obliterates the creation date:

for f in "$@"
do
    # convert video
    HandBrakeCLI -i "$f" -o "/Users/J/Desktop/$(basename $f .AVI).mp4" -e x264 -q 20 -B 160

    # read out creation date from source file
    date_transfer=$(stat -f "%Sm" "$f")     # output e.g.: Oct 27 16:33:41 2013

    # write creation date of source to converted file
    touch -t $date_transfer /Users/J/Desktop/$(basename $f .AVI).mp4  # requires 201310271633 instead
done
Palec
  • 12,743
  • 8
  • 69
  • 138
Jax
  • 13
  • 2

3 Answers3

1

Conversion of time format could be done via date utility:

On Linux (GNU coreutils):

$ date -d 'Oct 27 16:33:41 2013' '+%Y%m%d%H%M'
201310271633

On OS X (date options taken from Darwin manpages available online):

$ date -j -f '%b %d %T %Y' 'Oct 27 16:33:41 2013' '+%Y%m%d%H%M'
201310271633

Your code should look like this (on OS X):

for f in "$@"
do
   # convert video
   HandBrakeCLI -i "$f" -o "/Users/J/Desktop/$(basename "$f" .AVI).mp4" -e x264 -q 20 -B 160

   # read out creation date from source file
   date_transfer=$(stat -f '%Sm' "$f")

   # write creation date of source to converted file
   touch -t $(date -j -f '%b %d %T %Y' "$date_transfer" '+%Y%m%d%H%M') /Users/J/Desktop/$(basename "$f" .AVI).mp4
done

Notice the quotes around $date_transfer. Date wants to get the date as one parameter and shell would split parts of date_transfer at spaces if the quotes were not present.

Palec
  • 12,743
  • 8
  • 69
  • 138
1

You don't need to fight date formatting: use touch -r refFile fileToBeChanged

Your code would look like:

for f in "$@"
do
   # convert video
   HandBrakeCLI -i "$f" -o "/Users/J/Desktop/$(basename $f .AVI).mp4" -e x264 -q 20 -B 160

   # transfer creation date of source to converted file
   touch -r "$f" /Users/J/Desktop/$(basename $f .AVI).mp4
done
Palec
  • 12,743
  • 8
  • 69
  • 138
glenn jackman
  • 238,783
  • 38
  • 220
  • 352
  • Hi Glenn, well spotted. This makes the script much simpler and circumvents the messy date conversion. Thanks. – Jax Oct 28 '13 at 09:06
0

Try: date -d$date_transfer +%Y%m%d%H%M

formatted_date=$(date -d$date_transfer +%Y%m%d%H%M)

touch -t $formatted_date /Users/J/Desktop/$(basename $f .AVI).mp4

Community
  • 1
  • 1
Lachezar
  • 6,523
  • 3
  • 33
  • 34
  • This will not work on OS X, due to differencies in `date` utility options. I have already provided a more complete answer. – Palec Oct 28 '13 at 09:25