Reputation:
I'm trying to write a bash script to identify empty files within a directory. For ease of use, I plan on just saving it to the home directory and running it from there. Note that it to NOT be recursive. Trying to avoid the use of the find command as it can get messy. If you have a better suggestion than test, I am all ears.
I will say that I am fairly new to bash scripting and would normally do this in Python, but am looking to keep things consistent with what we do around here.
The output should be the list of any empty files and a counter. Below is what I have so far, but I am not returning empty files despite having numerous ones in the "test" directory.
fileCount=0
for item in *; do
if test -f "$item" && ! test -s "$item"
then
fileCount=$((fileCount+1))
echo $item
else
continue
fi
done
echo "Number of empty files: " $fileCount
If I wanted to modify this to take an argument (user-specified directory), how might I go about this? Below is how I have modified it, but I believe I am having an issue with my variables.
fileCount=0
echo "Please enter a directory: "
read directory
for item in $directory; do
if test -f "$item" && ! test -s "$item"
then
fileCount=$((fileCount+1))
echo $item
else
continue
fi
done
echo "Number of empty files: " $fileCount
Upvotes: 1
Views: 455
Reputation: 746
Actually, find
is very simple.
find . -type f -size 0
gives you all the empty files in the current directory.
find . -type f -size 0 | wc -l
gives you the number of empty files.
This works even with hidden files.
If you want to list empty files only within the current directory, just add -maxdepth 1
option to find.
Upvotes: 2
Reputation: 36229
find PATH_TO_SEARCH -maxdepth -type f -empty | nl
example:
find proj/mini/forum -maxdepth 1 -type f -empty | nl
1 proj/mini/forum/resolv
2 proj/mini/forum/five
3 proj/mini/forum/0
4 proj/mini/forum/FactorialComplexit.java
5 proj/mini/forum/-temp.html
6 proj/mini/forum/index.-temp.html
I can't see any messyness. Since in almost all cases, filenames don't span over multiple lines, while I have to admit it is possible, nl seems a good enough tool for measuring the number of empty files met.
Upvotes: 1
Reputation: 780879
break
ends the loop, so you stop counting at the first non-empty file. You want continue
, which goes to the next iteration of the loop.
Or you could just write:
if test -f "$item" && ! test -s "$item"
then
fileCount=$((fileCount+1))
fi
Upvotes: 3