Question

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 
Was it helpful?

Solution

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.

OTHER TIPS

Like William said, you can use -print. However, instead of -print > log, you can also use the -fprint flag.

You'd want something like:

find <PATH> -type f -name "<filePattern>" -mtime +1 -fprint "<pathToLog>" -delete

For instance, I use this in a script:

find . -type d -name .~tmp~ -fprint /var/log/rsync-index-removal.log -delete

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top