0

First linux coding job.

Told to make a script for a chron job that dives through all folders on server and deletes any files over X days (probably 20).

I have tested the code below on my home Redhat box.

Of course I have many trepidations before I promote this code to actual usage. Code below works fine, BUT I also need it to delete ONLY files (and NOT directories) OVER "X" number of days.

Cannot download, make any modifications to the system of hundreds of directories and thousands of files. The first time I run this, I expect to delete over 10,000 files, as our clients leave their files on our servers and forget about them. (This will wake them up!)

I tried changing line five, "elif [ -f "$i" -a -mtime +21 ]; then" -remove file (rm -i "$1")

Doesn't work, saying "[: mtime: binary operator expected"

Do I need another elif statement, or can I make the selection criteria (files only and just those over "X" days) work on one line?

CODE:

#!/bin/bash 

print_folder_recurse() {
    for i in "$1"/*; do
        if [ -d "$i" ]; then
            print_folder_recurse "$i"
        elif [ -f  "$i" ]; then
            rm -i  $i #(put the -i in there for #testing, it will be removed)
        fi    
    done
}

path "/go/to/your/happy/place"

echo "Delete path: $path"
print_folder_recurse $path

Thank you.

4
  • Or use the systemd tool that's built for the job... Commented Nov 10, 2019 at 21:01
  • You are using $1 and $i in the same script. What is the $i about? Does it work (better) if you switch to using $1 consistently? Commented Nov 10, 2019 at 22:41
  • @linux-fan I believe doing that would cause an infinite loop Commented Nov 10, 2019 at 22:52
  • Thanks, I see it now :) Commented Nov 10, 2019 at 22:53

1 Answer 1

1
find /your/directory -type f -daystart -mtime +20 -delete

Remove the -delete to perform a dry run.

4
  • Excellent answer. but I am now informed, if there is only one file in the directory, do not delete it. (please don't ask me why). Commented Nov 11, 2019 at 2:02
  • I'm thinking to do some kind of find . -type f | wc -l >dirs.txt, sort it, and then read in only those directories with multiple files using some kind of xargs into the statement above? Commented Nov 11, 2019 at 2:07
  • 1
    That’s a different, more difficult question. Given that the parameters are significantly different, please ask a new question. Commented Nov 11, 2019 at 6:58
  • Thanx.Will do. Gonna hack at it for a while first. Commented Nov 11, 2019 at 12:35

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.