29

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?

53

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
2

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.

  • this is really just a longer way of saying what Eric said. – Jeff Schaller Apr 9 '18 at 17:07
  • Well, for me the negative if ! grep ... statement did not work. So this is an alternative. – ssanch Apr 10 '18 at 17:33
1

I solve it with simple one liner:

for f in *.txt; do grep "tasks:" $f || echo $f; done

The command will check all files in the directory with txt extension and either write the search string (i.e. "tasks:") if found or else the name of the file.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.