Search code examples
bashif-statementnullgrep

How can I check if 'grep' doesn't have any output?


I need to check if the recipient username is in file /etc/passwd which contains all the users in my class, but I have tried a few different combinations of if statements and grep without success. The best I could come up with is below, but I don't think it's working properly.

My logic behind it is that if the grep is null, the user is invalid.

send_email()
{
  message=
  address=
  attachment=
  validuser=1
  until [ "$validuser" = "0" ]
    do
    echo "Enter the email address: "
    read address
    if [ -z grep $address /etc/passwd ]
      then
    validuser=0
    else
        validuser=1
    fi
    echo -n "Enter the subject of the message: "
    read message
    echo ""
    echo "Enter the file you want to attach: "
    read attachment
    mail -s "$message" "$address"<"$attachment"
    done
    press_enter
}

Solution

  • Just do a simple if like this:

    if grep -q $address  /etc/passwd
    then 
       echo "OK";
    else
       echo "NOT OK";
    fi
    

    The -q option is used here just to make grep quiet (don't output...)