Skip to content
Advertisement

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?

Advertisement

Answer

-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: %qn' "$hour" >&2
  exit 1
esac
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement