I am following a series of tutorials to learn Bash shell script. One of the exercises is to loop through files in the current directory and search for a pattern in those files. If the pattern is found then the script should sum the file size of those files.
#!/bin/sh
patern=echo
totalSize=0
for file in *
do
[ ! -f $file ] && continue
if grep $patern $file > /dev/null
then
echo "pattern matched in $file"
echo "file size is `stat -c%s $file`"
fileSize=`stat -c%s $file`
totalSize=`expr $totalSize + $fileSize`
echo "size so far is $totalSize bytes"
echo
fi
done
I have one other folder in the directory from which I am running the script. The folder is called "somedir". It is empty. I have took a snippet of output text pasted below. The middle 3 lines show when the loop iterates over the directory "somedir" which it prints as "sum_files"- my script name along with a file size.
I don't understand this behaviour. How can an empty directory have a file size?
But my main concern is as to why the continue keyword is not stopping the loop iteration. The output is showing that the script is running the below if statement containing the grep command even though it should stop if a directory is found.
I have verified that the test command[ ! -f $file ]
does in fact return 0 when the loop gets to the directory and thus the && continue
should be invoked. So why does the program continue with the rest of the loop code and try to grep the directory rather than just skipping the loop iteration at continue as expected? I know this is rather trivial but would like to know what's going on here.
Output text
pattern matched in retirement
file size is 396
size so far is 6385 bytes
pattern matched in sum_files
file size is 398
size so far is 6783 bytes
pattern matched in tp0
file size is 164
size so far is 6947 bytes