Skip to content
Advertisement

How to use grep in shell with -e option set

In bash -e option stops executing after an error and grep commands returns a non-zero status in case it does not find for the pattern it is looking for. I want to use grep inside an if statement, something like

#/bin/bash -e
if [[ `grep str /usr/lib/file.txt` -eq 0 ]]
  //do something
fi

If i use $? to get the statement of last command, then the execution stops after last command as grep returns non-zero status. There must be some way to accomplish this, need help finding it

Advertisement

Answer

Just do it in-place:

#/bin/bash -e
if grep -q str /usr/lib/file.txt; then
    echo "Found str"
else 
    echo "Didn't find str"
fi

Note the -q (--quiet) option of grep, we are only interested in the exit status.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement