So I need to check if the recipient username is in /etc/passwd which contains all the users in my class, but I have tried a few different combinations of if statements and g
Your piece of code
if [ -z grep $address /etc/passwd ]
You haven't save 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
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...)
easiest one will be this
$ cat test123
12345678
$ cat test123 | grep 123 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist"
grep result exist
$ cat test123 | grep 999 >/dev/null && echo "grep result exist" || echo "grep result doesn't exist"
grep result doesn't exist
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) ]
Use getent and check for grep's exit code. Avoid using /etc/passwd. Equivalent in the shell:
> getent passwd | grep -q valid_user
> echo $?
0
> getent passwd | grep -q invalid_user
> echo $?
1