Skip to content
Advertisement

Preserve timestamp when editing file

I want to preserve the timestamp of the files I’m editing in a for loop

for files in $DIR/MDC*/$FILE
do
    # Need to get date here!
    dos2unix $files
    if grep -q $TYPE $files; then
        echo 'done'
    else
        sed -i "1s/^/$TYPEn/" $files
    fi
    $DIR/crccalc/LDDR16.py $files
    # Use Date variable here to change it back

done

The issue is I need to get a formatted date string from the file so that I can do touch -r to revert the files date back once the loop has completed.

stat is not giving the me the format I need.

Required Format:

YYMMDDhhmm

Advertisement

Answer

There is a nice trick for this: using touch -r reference_file. That is, touch the file using the timestamp of another file as a reference.

From man touch:

   -r, --reference=FILE
          use this file's times instead of current time

And you may be asking: and how can this help you? Well, because you can create a dummy file dummy to work with:

  • Before modifying a file you touch the dummy with the timestamp of the file original_file you want to modify.
  • You modify the original_file.
  • Then you touch the original_file using the timestamp of the dummy one.

All together:

for files in $DIR/MDC*/$FILE
do
    # copy its timestamp to `dummy_file`
    touch -r "$files" "dummy_file"

    # ...things...

    # Use Date variable here to change it back
    touch -r "dummy_file" "$files"
done
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement