The top voted answers fail if no results were returned by a grep.
Homer Simpson
Marge Simpson
Bart Simpson
Lisa Simpson
Ned Flanders
Rod Flanders
Todd Flanders
Moe Szyslak
This is the wrong way to do it:
wiggums=$(grep -iF "Wiggum" characters.txt);
num_wiggums=$(echo "$wiggums" | wc -l);
echo "There are ${num_wiggums} here!";
There will tell us, there is 1
Wiggum in the list, even if there aren't any.
Instead, you need to do one extra check to see if the variable is empty (-z
, as in "is zero"). If grep didn't return anything, the variable will be empty.
matches=$(grep -iF "VanHouten" characters.txt);
if [ -z "$matches" ]; then
num_matches=0;
else
num_matches=$(echo "$matches" | wc -l);
fi
echo "There are ${num_matches} VanHoutens on the list";