Linux find and delete files but redirect file names to be deleted

Viewed 15905

Is there a way to write the file names to a file before they are deleted for reference later to check what has been deleted.

find <PATH> -type f -name "<filePattern>" -mtime +1 -delete 
5 Answers

Just add a -print expression to the invocation of find:

find <PATH> -type f -name "<filePattern>" -mtime +1 -delete -print > log

I'm not sure if this prints the name before or after the file is unlinked, but it should not matter. I suspect -delete -print unlinks before it prints, while -print -delete will print before it unlinks.

You can use -exec and rm -v:

find <PATH> -type f -name "<filePattern>" -mtime +1 -exec rm -v {} \;

rm -v will report what it is deleting.

With something like this you can execute multiple commands in the exec statement, like log to file, rm file, and whatever more you should need

find <PATH> -type f -name "<filePattern>" -mtime +1 -exec sh -c "echo {} >>mylog; rm -f {}" \;

From a shell script named removelogs.sh run the command sh removelogs.sh in terminal

this is the text in removelogs.sh file.

cd /var/log;
date >> /var/log/removedlogs.txt;
find . -maxdepth 4 -type f -name \*log.old -delete -print >> /var/log/removedlogs.txt
  • . - to run at this location !!! so ensure you do not run this in root folder!!!
  • -maxdepth - to prevent it getting out of control
  • -type - to ensure just files
  • -name - to ensure just your filtered names
  • -print - to send the result to stdout
  • -delete - to delete said files
  • >> - appends to files not overwrites > creates new file

works for me on CENTOS7

Related