Shell – How to bump file timestamps by 3 months (for a directory tree)

findshelltouch

I am looking at the touch command line utility (on Linux), and from the examples I found in tutorials, I see how one can bump the access or modification timestamp to a specified time, the current time, or to a reference file.

However, I would like to do the following: The relative age of my files (relative to each other) has information valuable to me, and I'd rather not lose that. But I need each file in (recursive) folders look a few months younger than they are. So each file could refer to itself, bump the time, but apply this to each file in a tree of folders. What is a good way to do this?

#!/bin/bash
FILES=$(find $HIGHEST_FOLDER -type f -name *.*)
for f in $FILES
do
  touch -ram f -F 7776000 f
  # bumping access and modification timestamps by 3 months?
done

Or am I better off using find -exec as suggested in this answer? (There are many files in these folders.) How could that work?

Best Answer

Assuming your are on a Linux system, or at least that you have GNU touch and GNU date, you can do (in bash; zsh is the same but does not need the shopt globstar):

$ shopt globstar
$ for f in **; do 
    touch -d "$(date -d "$(stat -c '%y' "$f") +3 months")" "$f"
  done

That, however, will ignore hidden files. To match those as well, run shopt -s dotglob before the above commands.

Explanation

  • shopt -s globstar : This sets bash's globstar option which means that ** will match all files and zero or more directories and subdirectories.
  • shopt -s dotglob: makes * (and **) also match files whose names begins with a ..
  • for f in **; do ...; done : iterate over all files and directories, saving them as $f.
  • stat -c '%y' "$f" : this is the current time stamp of the current file or directory.
  • date -d $(...) +3 months : print the date that is three months after the given string (in this case, that string is the output of the stat command on $f).

All together, the above will find the modification date of each file or directory in the current folder (including all subdirectories) and set its date three months after whatever it is now.

Related Question