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?



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)

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

echo "Delete path: $path"
print_folder_recurse $path

Thank you.

  • Or use the systemd tool that's built for the job...
    – Jeff Schaller
    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?
    – linux-fan
    Nov 10, 2019 at 22:41
  • @linux-fan I believe doing that would cause an infinite loop
    – bxm
    Nov 10, 2019 at 22:52
  • Thanks, I see it now :)
    – linux-fan
    Nov 10, 2019 at 22:53

1 Answer 1

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

Remove the -delete to perform a dry run.

  • 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). 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? 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.
    – bxm
    Nov 11, 2019 at 6:58
  • Thanx.Will do. Gonna hack at it for a while first. Nov 11, 2019 at 12:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .