grep
can take file as an argument, you don't need to cat
the file and then pass the content to grep
with pipe, that's totally unnecessary.
This is an example of if else
block with grep
:
if grep -q "pattern" filepath;then
echo "do something"
else
echo "do something else"
fi
Note:
-q
option is for quite operation. It will hide the output of grep
command (error will be printed).
If you want it to not print any errors too then use this:
if grep -sq "pattern" filepath;then
Or this:
if grep "pattern" filepath >/dev/null 2>&1;then
>/dev/null
is to redirect the output to /dev/null
2>&1
redirects both stderr and stdout