Issue
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
Solution
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"
Answered By - Gilles Quenot Answer Checked By - Mildred Charles (WPSolving Admin)