1

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.

4 Answers 4

2

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

{ id "alice" && id "bob" && id "carol"; } >/dev/null 2>&1
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. But how to print a message, let's say alice is not present?
I get the error as test.sh: line 16syntax error near unexpected token `if' test.sh: line 16: `if ! id "$u" >/dev/null 2>&1; then '
Sorry do is missing. Use: for u in alice bob carol; do if ! id "$u" >/dev/null 2>&1; then echo "$u does not exist"; fi; done
0

You can redirect the stderr of each command:

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

Oor use a compound command:

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

Comments

0

Use the || as you did with && :

{ test1 && test2 && test3 } || else_function

If your request is to show all unset users, it is a bit more tricky, but use negative check:

{ ! id "alice" && echo "alice absent." } || { ! id "bob" && echo "bob absent." } || { ! id "walter" && echo "walter absent." }

or even:

absent=false
for user in alice bob walter ; do
   ! id "$user" && echo "$user is absent." && absent=true
done
$absent || echo "All users are present."

Comments

0

I think the general answer is that if you want a specific error, you need a specific test. That is, if you test for ( condA || condB || condC ), it's not straightforward to find out which of those conditions failed.

Also, if you want to test them all, no matter what, you'll need to break them out into separate tests. Otherwise if id "alice" fails, the others won't get tested due to short circuiting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.