Im trying to write a script that can search the current directory for empty files, followed by a count of the empty files. I would also prefer the files to be one per line of the output. For example the program output would look like:
Empty files are: file1.pdf file4.cpp example-file Number of empty files: 30
3 Answers
If you don't need to recurse (i.e. descend into / count empty files inside subdirectories) then you can just use standard file tests e.g.
n=0
for f in *; do [[ -f "$f" ]] && [[ ! -s "$f" ]] && { echo "$f"; ((n++)); }
done
echo "Number of empty files: $n"From help test:
-f FILE True if file exists and is a regular file. -s FILE True if file exists and is not empty. 2 Size of the empty file is typically zero. So running the following script will help to find the empty files
find /home/ -type f -size oc -exec ls {} \;
As units you can use:
b – for 512-byte blocks (this is the default if no suffix is used)
c – for bytes
w – for two-byte words
k – for Kilobytes (units of 1024 bytes)
M – for Megabytes (units of 1048576 bytes)
G – for Gigabytes (units of 1073741824 bytes)i created some empty files and kept it in the following directory
/home/um/Documents/hello
Now lets see all the empty files that i have created
cd /home/um/Documents/hello This command changes the directory to hello
ls -sh It list all the files including the size in human readable format in /home/um/Documents/hello
16K empty.odt 12K empty.pdf 8.0K empty.txt 16K excel.ods
However the size of these files are in the range of 0 - 20 kb I am sure these file are empty
So it is possible to sort all files based on size.
find /home/um/Documents/hello -type pdf -size -20k -exec ls -lh {} \;
It sort all the files that are lesser than 20kb
You can use the find command to look for empty files
find . -maxdepth 1 -type f -empty | tee /dev/tty | wc -lWhere
-maxdepth 1only look in current directory and not subdirectories-type flooks only for files, not directories-emptychecks for empty filestee /dev/ttysend filename to the terminal and to wcwc -lcount the files
See man find for more information.