Tony
Tony

Reputation: 9591

Bash -eq evaluates to true?

Can someone help me figure out why my code below results in the output below? Specifically when there is no string in /etc/passed that matches?

CODE:

for user in ${usernames[*]}
do
egrep ${user} /etc/passwd >/dev/null
echo -e "\nChecking if users already exist..."
if [ $? -eq 0 ]; then
echo -e "${user} exists!, skipping creation"

OUTPUT:

+ for user in '${usernames[*]}'
+ egrep addaf /etc/passwd
+ echo -e '\nChecking if users already exist...'
Checking if users already exist...
+ '[' 0 -eq 0 ']'
+ echo -e 'addaf exists!, skipping creation'
addaf exists!, skipping creation

Upvotes: 1

Views: 81

Answers (1)

tripleee
tripleee

Reputation: 189628

You are examining the exit code from echo, which is always a success.

Anyway, the idiomatic way to do that is

if grep -Eq "$user" /etc/passwd; then
    ...

Generally, you should almost never need to examine $? explicitly.

Upvotes: 5

Related Questions