Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

bash - 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

62 comments

56.6k users

...