Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 } 
like image 828
Duncan Avatar asked Dec 10 '14 02:12

Duncan


People also ask

How do I grep without output?

To suppress the default grep output and print only the names of files containing the matched pattern, use the -l ( or --files-with-matches ) option.

What does grep return if nothing found?

Indeed, grep returns 0 if it matches, and non-zero if it does not. Hence my comment. In the shell 0 means success.

How do I get grep output?

To Show Lines That Exactly Match a Search String The grep command prints entire lines when it finds a match in a file. To print only those lines that completely match the search string, add the -x option. The output shows only the lines with the exact match.


1 Answers

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

like image 92
Marcellus Avatar answered Oct 17 '22 08:10

Marcellus