1

I followed the following thread How to create a bash script in Linux that checks if the user is local or not

I want to check number of arguments number received before checking the username

username=$1                                                                     
                                                                                
id -u $username > /dev/null 2>&1                                                
                                                                                
if [ $# -gt 0 ]; then                                                           
 if [ $? -eq 0 ]; then                                                          
  echo "$username exists"                                                       
  else                                                                          
  echo "$username doesn't exist"                                                
  fi                                                                            
else                                                                            
echo "num of arg are less than expected"                                        
fi      

the script doesn't work properly, it always writes that the user exists

3

1 Answer 1

4

As explained by Cyrus in comments, you are trying to test $? at the wrong place, because the test or [ command set $? too.

Better use this:

if getent passwd "$username" &>/dev/null; then
    echo 'user exists'
else
    echo 'user NOT exists'
fi

The getent password <username>, if not match a user, exit with a return code >= 1.
It's boolean logic. No need to test $?.

The same logic appears with id:

id nonexistant || echo "not exists"
Sign up to request clarification or add additional context in comments.

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.