2

I need to create a bash script that deletes all files older than N days in downloads folder but would exclude all files in archive sub-folder. My folder structure is like this:

downloads/
   user1_folder/
      archive/
   user2_folder/
      archive/
   ...

Based on this Q&A I was able to create script that finds and deletes files older than N days, but I would like to exclude all files in archive subfolders.

#!/bin/bash
find ./downloads -mtime +32 -type f -delete
Cœur
  • 37,241
  • 25
  • 195
  • 267
Primoz Rome
  • 10,379
  • 17
  • 76
  • 108
  • You'll have to play with maxdepth parameter – Juan Diego Godoy Robles May 20 '14 at 06:03
  • What's your specific scenario? Using mtime (last modified time) could cause problems. For instance, if a file is copied from another location and added to one of your user folders, the change time will update but the last modified time will not. – Usagi May 20 '14 at 07:06
  • @Usagi I want to have a cronjob and delete all files in downloads folder which are older then 4 weeks. Meaning were added into the downloads folder before that time... you might have a point here with modified time. – Primoz Rome May 20 '14 at 07:10
  • @Usagi do you recommend using ctime instead? I found a great explanation between atime, mtime and ctime and seems pretty clear that ctime is the best way to go http://www.linux-faqs.info/general/difference-between-mtime-ctime-and-atime – Primoz Rome May 20 '14 at 07:29
  • Yes, I think you should be able to avoid most all problems with ctime given your situation. – Usagi May 20 '14 at 08:00

2 Answers2

2

Try:

find ./downloads -maxdepth 2 -type f -mtime +32 -delete

-maxdepth levels Descend at most levels (a non-negative integer) levels of directories below the command line arguments. -maxdepth 0 means only apply the tests and actions to the command line arguments.

Juan Diego Godoy Robles
  • 14,447
  • 2
  • 38
  • 52
0

Adding ! -path (your path) should do the trick

find ./downloads ! -path ./downloads/*/archive/* -mtime +32 -type f -delete
Jonathan Wheeler
  • 2,539
  • 1
  • 19
  • 29
  • Works fine unless there are more the 1 files in archive folders. In this case the command `find ./fuel/app/downloads ! -path ./fuel/app/downloads/*/archive/* -mtime +32 -type` will return `find: ./fuel/app/downloads/primoz-rome-sp/archive/image001-3.png: unknown primary or operator` – Primoz Rome May 20 '14 at 06:14
  • Then you can replace the first asterisk with [^/]* – Jonathan Wheeler May 20 '14 at 06:17
  • Promising, but you need to _quote_ your pattern to prevent premature expansion by the _shell_; also, it's better to use `-not` instead of `!` to prevent conflicts with the history expansion feature in interactive shells; thus: `-not -path './downloads/*/archive/*'` – mklement0 May 20 '14 at 06:17