Bash script search and delete files older than actual time

Hi all,

I need a guid to understand how I can write a script to search specific ext file *.aud , need to compare the the date of this files with the actual time if they are older I will need to delete them.

Im looking all the options I found but not havin any luck.

thanks.

Hi @Juraj_Papic,

Welcome to nixCraft forum.

Have you written in code? If so past it here.

Typically you need to use the find command. For example find files older than 60 days,

## files only ##
find /path/to/dir/ -type f -mtime +60 -ls
## dirs only ##
find /path/to/dir/ -type d -mtime +60 -ls

Replace the ls with -delete to remove files. Be careful, as you might end up deleting important files. Hence always run -ls option first to check about files. Always keep backups. You have been warned.

find /path/to/dir/ -type f -mtime +60 -delete
## OR confirm it before removing it ## 
find /path/to/dir/ -type f -mtime +60 -exec /bin/rm -i {} \;

Explanation

  1. find : Find command
  2. /path/to/dir/ : Directory path to search
  3. -type f : Only works on files. (the -type d option only works on dirs)
  4. -mtime +60 : Select file with modification time older than 60 days
  5. -exec /bin/rm -i {} \; : Delete file with confirmation
  6. -delete - Delete file
  7. -ls : list file
1 Like

Thanks I will test that today.