Bash – How to use grep when file does not contain the string

bashgrepUbuntu

In my bash script I'm trying to print a line if a certain string does not exist in a file.

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

This is how I wrote it if I wanted the string to exist in the file but how can I change this to make it print "user does not exist" if the user is not found in the /etc/passwd file?

Best Answer

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
Related Question