kingmakerking kingmakerking - 26 days ago 9
Bash Question

Find out if unix user names (multiple) exists using shell script

I have the following script which checks whether the given username "alice" exists in the system.

if id "alice" >/dev/null 2>&1; then
echo "user exists"
else
echo "user does not exist"
fi


I want to check whether alice, bob and carol exists. So, when I use AND in the following code, I do get the right results probably, but it prints the unnecessary line from id command.

if id "alice" && id "bob" && id "carol" >/dev/null 2>&1; then
echo "user exists"
else
echo "user does not exist"
fi


The output is as follows:

uid=1001(alice) gid=1002(alice) groups=1005(somegroupname),1002(alice)
uid=1002(bob) gid=1003(bob) groups=1005(somegroupname),1003(bob)
user exists


I want to make sure that if alice, bob or carol are not present as users, I want to print a meaningful message stating

<this_speicific_user> is not present.

Answer Source

You can use braces to group all 3 commands into one group:

{ id "alice" && id "bob" && id "carol"; } >/dev/null 2>&1