Home > database >  A bash script that will compare the creation time of all files in a directory to a timestamp stored
A bash script that will compare the creation time of all files in a directory to a timestamp stored

Time:05-17

Good day.

I'm trying to create a bash script that will compare all files in a directory to a specific timestamp. This timestamp is stored in a variable. If the file creation date varies from the timestamp by a few seconds, it will print the filename.

It seems like the best fit would be the find command. So far I've tried:

find /directory/*.txt -type -f -newer $TimestampVariable
(with $TimestampVariable="Wed May 11 13:53:20 EDT 2022")

as a jumping off point. But that isn't going to work because it isn't reading the timestamp in the variable, and it isn't comparing it to a range of times between $TimestampVariable and five seconds later.

CodePudding user response:

With GNU and BSD find you can use the -newerXY predicate.

For example, if you search for all the files modified in between Wed May 11 13:53:20 EDT 2022 and Wed May 11 13:53:25 EDT 2022 then you could do:

find . -type f -newermt 'Wed May 11 13:53:19 EDT 2022' -not -newermt 'Wed May 11 13:53:26 EDT 2022'

Then, given a timestamp variable in the following format:

TimestampVariable="Wed May 11 13:53:20 EDT 2022"

Here's how you can generate the two dates needed for the -newerXY predicates (I chose to generate the dates in ISO-8601 format because it's well supported).

  • on Linux:
min=$(date -d "$TimestampVariable -1sec" --iso-8601=second)
max=$(date -d "$TimestampVariable  6sec" --iso-8601=second)
  • on macOS:
min=$(date -j -v-1S -f '%a %b %d %T %Z %Y' "$TimestampVariable"  %Y-%m-%dT%T%z)
max=$(date -j -v 6S -f '%a %b %d %T %Z %Y' "$TimestampVariable"  %Y-%m-%dT%T%z)

Now you can do:

find . -type f -newermt "$min" -not -newermt "$max"
  • Related