1

I need a script that removes all empty files and writes a list of deleted files to a text file.

Deleting files works. Unfortunately, the listing does not work.

find . -type f -empty -print -delete

I tried something like this:

-print >> test.txt
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • 1
    Works for me. What output do you get? – joanis Jan 18 '22 at 21:24
  • @joanis Yes, it works. I get the output. But I want to send it to a file. This means - each deleted file -> its name saved in the test.txt file – cristoferro061 Jan 18 '22 at 21:25
  • 1
    Ah, interesting problem: when I redirect the output to a file in `.`, the command itself deletes it before anything gets written to it, so it goes missing. Try `find . -type f -empty -print -delete > ../output` – joanis Jan 18 '22 at 21:25

2 Answers2

5

When I redirect the output of your command to a file in ., it gets delete by the find command before anything is written to it, since it is empty.

To solve this, make sure the output file is not empty at the beginning, or save it elsewhere:

find . -type f -empty -print -delete > ../log

or

date > log
find . -type f -empty -print -delete >> log

or, adapted from @DanielFarrell's comment:

find . -type f -empty -a -not -wholename ./log  -print -delete > log

The added -a -not -wholename ./log excludes ./log from the find operation.

joanis
  • 10,635
  • 14
  • 30
  • 40
2

You can use -exec option with rm command instead of -delete.

find . -type f -emtpy -exec rm --verbose {} \; >> logfile.txt

logfile.txt:

removed './emptyfile1'
removed './emptyfile0'

Or you can use pipes and xargs for a more clean output:

find . -type f -empty | xargs ls | tee -a logfile.txt | xargs rm

This will give you only deleted filenames.

acfglmrsx
  • 52
  • 3
  • When I run either of these commands, `logfile.txt` still gets deleted, unless if was already non-empty before the `find` starts. – joanis Jan 24 '22 at 13:19