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

121,778

Solution 1

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...)

Solution 2

Use getent and check for grep's exit code. Avoid using /etc/passwd. Equivalent in the shell:

getent passwd | grep -q valid_user
echo $?

Output:

0

And:

getent passwd | grep -q invalid_user
echo $?

Output:

1

Solution 3

Your piece of code:

if [ -z grep $address /etc/passwd ]

You haven't saved the results of grep $address /etc/passwd in a variable. Before putting it in the if statement and then testing the variable to see if it is empty.

You can try it like this:

    check_address=`grep $address /etc/passwd`
    if [ -z "$check_address" ]
      then
    validuser=0
    else
        validuser=1
    fi

Solution 4

The easiest one will be this:

cat test123

# Output: 12345678

cat test123 | grep 123 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist"

# Output: grep result exist

cat test123 | grep 999 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist"

# Output: grep result doesn't exist

Solution 5

The -z check is for variable strings, which your grep isn't giving. To give a value from your grep command, enclose it in $():

if [ -z $(grep $address /etc/passwd) ]
Share:
121,778
Duncan
Author by

Duncan

Updated on September 17, 2021

Comments

  • Duncan
    Duncan over 2 years

    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
    }