How to use grep when file does not contain the string

grep will return success if it finds at least one instance of the pattern and failure if it does not. So you could either add an else clause if you want both "does" and "does not" prints, or you could just negate the if condition to only get failures. An example of each:

if grep -q "$user2" /etc/passwd; then
    echo "User does exist!!"
else
    echo "User does not exist!!"
fi

if ! grep -q "$user2" /etc/passwd; then
    echo "User does not exist!!"
fi

An alternative is to look for the exit status of grep. For example:

grep -q "$user2" /etc/passwd
if [[ $? != 0 ]]; then
    echo "User does not exist!!"

If grep fails to find a match it will exit 1, so $? will be 1. grep will always return 0 if successful. So it is safer to use $? != 0 than $? == 1.


You can use the grep option "-L / --files-without-match", to check if file does not contain a string:

if [[ $(grep -L "$user2" /etc/passwd) ]]; then   
  echo "User does not exist!!"; 
fi

Tags:

Bash

Ubuntu

Grep