Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file is older than 30 minutes in unix

I've written a script to iterate though a directory in Solaris. The script looks for files which are older than 30 minutes and echo. However, my if condition is always returning true regardless how old the file is. Someone please help to fix this issue.

for f in `ls -1`;
# Take action on each file. $f store current file name
do
  if [ -f "$f" ]; then
  #Checks if the file is a file not a directory
  if test 'find "$f" -mmin +30'
  # Check if the file is older than 30 minutes after modifications
  then
     echo $f is older than 30 mins
  fi
 fi
 done
like image 700
user3484214 Avatar asked Dec 13 '25 13:12

user3484214


2 Answers

  1. You should not parse the output of ls
  2. You invoke find for every file which is unnecessarily slow

You can replace your whole script with

find . -maxdepth 1 -type f -mmin +30 | while IFS= read -r file; do
    [ -e "${file}" ] && echo "${file} is older than 30 mins"
done

or, if your default shell on Solaris supports process substitution

while IFS= read -r file; do
    [ -e "${file}" ] && echo "${file} is older than 30 mins"
done < <(find . -maxdepth 1 -type f -mmin +30)

If you have GNU find available on your system the whole thing can be done in one line:

find . -maxdepth 1 -type f -mmin +30 -printf "%s is older than 30 mins\n"
like image 96
Adrian Frühwirth Avatar answered Dec 16 '25 02:12

Adrian Frühwirth


Since you are iterating through a directory you could try the below command which will find all files ending with log type edited in the past 30 min. Using:

  • -mmin +30 would give all files edited before 30 minutes ago

  • -mmin -30 would give all files that have changed within the last 30 minutes

 

find ./ -type f -name "*.log" -mmin -30 -exec ls -l {} \;
like image 38
Melanie Avatar answered Dec 16 '25 03:12

Melanie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!