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 }
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.
Indeed, grep returns 0 if it matches, and non-zero if it does not. Hence my comment. In the shell 0 means success.
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.
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...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With