Reputation: 1458
I need to see if user exists in /etc/passwd
. I'm using grep, but I'm having a hard time passing multiple patterns to grep.
I tried
if [[ ! $( cat /etc/passwd | egrep "$name&/home" ) ]];then
#user doesn't exist, do something
fi
I used ampersand instead of | because both conditions must be true, but it's not working.
Upvotes: 0
Views: 384
Reputation: 189387
Contrary to your assumptions, regex does not recognize &
for intersection, even though it would be a logical extension.
To locate lines which match multiple patterns, try
grep -e 'pattern1.*pattern2' -e 'pattern2.*pattern1' file
to match the patterns in any order, or switch to e.g. Awk:
awk '/pattern1/ && /pattern2/' file
(though in your specific example, just "$name.*/home"
ought to suffice because the matches must always occur in this order).
As an aside, your contorted if
condition can be refactored to just
if grep -q pattern file; then ...
The if
conditional takes as its argument a command, runs it, and examines its exit code. Any properly written Unix command is written to this specification, and returns zero on success, a nonzero exit code otherwise. (Notice also the absence of a useless cat
-- almost all commands accept a file name argument, and those which don't can be handled with redirection.)
Upvotes: 0
Reputation: 185106
Try doing this :
$ getent passwd foo bar base
Finally :
if getent &>/dev/null passwd user_X; then
do_something...
else
do_something_else...
fi
Upvotes: 2