michaelpnrs
michaelpnrs

Reputation: 111

find files modified within given time range

Hello to everyone I'm trying to create a script to search files that modified between X:00-X:59. X is given by the user. I've tried this:

echo "Give hour: "
read N
if [ N>=0 && N<=24 ]
then
  find /home/mikepnrs -newermt "$N:00-59"
else
 echo "Out of bounds!"
fi

Any solutions?

Upvotes: 1

Views: 837

Answers (2)

oguz ismail
oguz ismail

Reputation: 50750

-newermt primary doesn't accept a time range in any format. To select files modified within let's say the period A-B, you need two -newermts; one to include files newer than A, the other to exclude files newer than B.

Further, there are two edge cases that need to be dealt with:

  1. The user might enter 08 or 09 as both are valid hours. But as both have a leading zero, Bash would treat them as octal numbers in an arithmetic context, and raise an error since 8 and 9 are not valid digits in base 8.
  2. When the user entered 0, to include files modified at 00:00 too, inclusive -newermt's argument has to be yesterday's 23:59:59.

So, I would do it like this instead:

#!/bin/bash -
LC_COLLATE=C
read -rp 'hour ([0]0-23): ' hour
case $hour in
(0|00)
  find /home/mikepnrs               \
      -newermt 'yesterday 23:59:59' \
    ! -newermt '00:59:59' ;;
(0[1-9]|1[0-9]|2[0-3])
  find /home/mikepnrs                  \
      -newermt "$((10#$hour-1)):59:59" \
    ! -newermt "$hour:59:59" ;;
(*)
  printf 'invalid hour: %q\n' "$hour" >&2
  exit 1
esac

Upvotes: 3

Dominique
Dominique

Reputation: 17493

It does not work like that: newerXY gives you the files which are newer than a particular timestamp, you can only give one condition (and you want two of them, "newer than X:00" and "older than "X+1:00".

I'd advise you to use find to find files "newer than X:00", and to use -ls at the end of the find, this gives you a listing like:

37436171902531110  0 -rw-rw-rw-   1 user   group   0 May 24 15:56 ./blabla_002.jpg
 2533274791505920  0 -rw-rw-rw-   1 user   group  55 May 26 15:13 ./test.txt
28147497671070312  0 -rw-rw-rw-   1 user   group   0 May 24 15:56 ./test_001.jpg
 8162774324885354  0 -rw-rw-rw-   1 user   group  25 Jun 17 10:22 ./try.txt
 2533274791505920  0 -rw-rw-rw-   1 user   group  55 May 26 15:13 test.txt
 8162774324885354  0 -rw-rw-rw-   1 user   group  25 Jun 17 10:22 try.txt

Using awk script, you can filter out the ones which are too new.

Upvotes: 0

Related Questions