0

I'm trying to run an auto-delete script to free up space on a remote server. The command I'm thinking to use is:
find . -atime +30 -mtime +30 -type f -delete

What I want is to also capture which files were successfully deleted and which failed because of access issue. How should I do this? I think this command below might take care of the failures only, but I'm not sure.
find . -atime +30 -mtime +30 -type f -delete 2>failed_deletions.txt

Harshit Jindal
  • 621
  • 8
  • 26
  • Related: [redirect stdout and stderr to a single file with prefixes](https://stackoverflow.com/q/2432535/45249) – mouviciel Sep 17 '21 at 08:14
  • Would advise you to please research a bit before posting because there are numerous questions/answers/discussions on the same topic. Anyway, have a read [here](https://stackoverflow.com/questions/11027679/capture-stdout-and-stderr-into-different-variables). Also, you can have a look at `exe`c & `trap` combinations to capture script executions. – vkeeWorks Sep 17 '21 at 10:35
  • If you want a log of failed an successful deletions, I would write a program that does its own iteration, file-stating, and file deletion using system calls directly, rather than forcing `find` and `rm` to do something they weren't designed to do. (There is a difference between *feedback* and *auditing*.) – chepner Sep 17 '21 at 11:45
  • Your approach deletes the files, but keeps the directory structure untouched. Is this intentional? – user1934428 Jan 07 '23 at 10:59
  • @user1934428 yes it is intentional, and `-type f` option was passed to `find` for this. – Harshit Jindal Jan 10 '23 at 13:56

2 Answers2

1

find out of the box does not print the files it processes. If you want to list the files, add a -print or -ls before the -delete.

This obviously prints all the files it processes, including the ones it fails to delete for whatever reason.

Redirecting standard output to a different file should be trivial to discover; command >stdout 2>stderr

The final command would become

find . -atime +30 -mtime +30 -type f \
    -print -delete >success.txt 2>errors.txt
tripleee
  • 175,061
  • 34
  • 275
  • 318
1

Less performant, but should do what you wanted:

find . -atime +30 -mtime +30 -type f -exec rm -v {} \; >successful.txt 2>failed.txt
user1934428
  • 19,864
  • 7
  • 42
  • 87