Check Whether a User Exists - bash

I want to create a script to check whether a user exists. I am using the logic below:
# getent passwd test > /dev/null 2&>1
# echo $?
0
# getent passwd test1 > /dev/null 2&>1
# echo $?
2
So if the user exists, then we have success, else the user does not exist. I have put above command in the bash script as below:
#!/bin/bash
getent passwd $1 > /dev/null 2&>1
if [ $? -eq 0 ]; then
echo "yes the user exists"
else
echo "No, the user does not exist"
fi
Now, my script always says that the user exists no matter what:
# sh passwd.sh test
yes the user exists
# sh passwd.sh test1
yes the user exists
# sh passwd.sh test2
yes the user exists
Why does the above condition always evaluate to be TRUE and say that the user exists?
Where am I going wrong?
UPDATE:
After reading all the responses, I found the problem in my script. The problem was the way I was redirecting getent output. So I removed all the redirection stuff and made the getent line look like this:
getent passwd $user > /dev/null
Now my script is working fine.

You can also check user by id command.
id -u name gives you the id of that user.
if the user doesn't exist, you got command return value ($?)1
And as other answers pointed out: if all you want is just to check if the user exists, use if with id directly, as if already checks for the exit code. There's no need to fiddle with strings, [, $? or $():
if id "$1" &>/dev/null; then
echo 'user found'
else
echo 'user not found'
fi
(no need to use -u as you're discarding the output anyway)
Also, if you turn this snippet into a function or script, I suggest you also set your exit code appropriately:
#!/bin/bash
user_exists(){ id "$1" &>/dev/null; } # silent, it just sets the exit code
if user_exists "$1"; code=$?; then # use the function, save the code
echo 'user found'
else
echo 'user not found' >&2 # error messages should go to stderr
fi
exit $code # set the exit code, ultimately the same set by `id`

There's no need to check the exit code explicitly. Try
if getent passwd $1 > /dev/null 2>&1; then
echo "yes the user exists"
else
echo "No, the user does not exist"
fi
If that doesn't work, there is something wrong with your getent, or you have more users defined than you think.

Why don't you simply use
grep -c '^username:' /etc/passwd
It will return 1 (since a user has max. 1 entry) if the user exists and 0 if it doesn't.

This is what I ended up doing in a Freeswitch bash startup script:
# Check if user exists
if ! id -u $FS_USER > /dev/null 2>&1; then
echo "The user does not exist; execute below commands to crate and try again:"
echo " root#sh1:~# adduser --home /usr/local/freeswitch/ --shell /bin/false --no-create-home --ingroup daemon --disabled-password --disabled-login $FS_USER"
echo " ..."
echo " root#sh1:~# chown freeswitch:daemon /usr/local/freeswitch/ -R"
exit 1
fi

By far the simplest solution:
if id -u "$user" >/dev/null 2>&1; then
echo 'user exists'
else
echo 'user missing'
fi
The >/dev/null 2>&1 can be shortened to &>/dev/null in Bash, and if you only want to know if a user does not exist:
if ! id -u "$user" >/dev/null 2>&1; then
echo 'user missing'
fi

I suggest to use id command as it tests valid user existence wrt passwd file entry which is not necessary means the same:
if [ `id -u $USER_TO_CHECK 2>/dev/null || echo -1` -ge 0 ]; then
echo FOUND
fi
Note: 0 is root uid.

I was using it in that way:
if [ $(getent passwd $user) ] ; then
echo user $user exists
else
echo user $user doesn\'t exists
fi

Script to Check whether Linux user exists or not
Script To check whether the user exists or not
#! /bin/bash
USER_NAME=bakul
cat /etc/passwd | grep ${USER_NAME} >/dev/null 2>&1
if [ $? -eq 0 ] ; then
echo "User Exists"
else
echo "User Not Found"
fi

Late answer but finger also shows more information on user
sudo apt-get finger
finger "$username"

Using sed:
username="alice"
if [ `sed -n "/^$username/p" /etc/passwd` ]
then
echo "User [$username] already exists"
else
echo "User [$username] doesn't exist"
fi

Actually I cannot reproduce the problem. The script as written in the question works fine, except for the case where $1 is empty.
However, there is a problem in the script related to redirection of stderr. Although the two forms &> and >& exist, in your case you want to use >&. You already redirected stdout, that's why the form &> does not work. You can easily verify it this way:
getent /etc/passwd username >/dev/null 2&>1
ls
You will see a file named 1 in the current directory. You want to use 2>&1 instead, or use this:
getent /etc/passwd username &>/dev/null
This also redirects stdout and stderr to /dev/null.
Warning Redirecting stderr to /dev/null might not be such a good idea. When things go wrong, you will have no clue why.

user infomation is stored in /etc/passwd, so you can use "grep 'usename' /etc/passwd" to check if the username exist.
meanwhile you can use "id" shell command, it will print the user id and group id, if the user does not exist, it will print "no such user" message.

Depending on your shell implementation (e.g. Busybox vs. grown-up) the [ operator might start a process, changing $?.
Try
getent passwd $1 > /dev/null 2&>1
RES=$?
if [ $RES -eq 0 ]; then
echo "yes the user exists"
else
echo "No, the user does not exist"
fi

Login to the server.
grep "username" /etc/passwd
This will display the user details if present.

Below is the script to check the OS distribution and create User if not exists and do nothing if user exists.
#!/bin/bash
# Detecting OS Ditribution
if [ -f /etc/os-release ]; then
. /etc/os-release
OS=$NAME
elif type lsb_release >/dev/null 2>&1; then
OS=$(lsb_release -si)
elif [ -f /etc/lsb-release ]; then
. /etc/lsb-release
OS=$DISTRIB_ID
else
OS=$(uname -s)
fi
echo "$OS"
user=$(cat /etc/passwd | egrep -e ansible | awk -F ":" '{ print $1}')
#Adding User based on The OS Distribution
if [[ $OS = *"Red Hat"* ]] || [[ $OS = *"Amazon Linux"* ]] || [[ $OS = *"CentOS"*
]] && [[ "$user" != "ansible" ]];then
sudo useradd ansible
elif [ "$OS" = Ubuntu ] && [ "$user" != "ansible" ]; then
sudo adduser --disabled-password --gecos "" ansible
else
echo "$user is already exist on $OS"
exit
fi

Create system user some_user if it doesn't exist
if [[ $(getent passwd some_user) = "" ]]; then
sudo adduser --no-create-home --force-badname --disabled-login --disabled-password --system some_user
fi

I like this nice one line solution
getent passwd username > /dev/null 2&>1 && echo yes || echo no
and in script:
#!/bin/bash
if [ "$1" != "" ]; then
getent passwd $1 > /dev/null 2&>1 && (echo yes; exit 0) || (echo no; exit 2)
else
echo "missing username"
exit -1
fi
use:
[mrfish#yoda ~]$ ./u_exists.sh root
yes
[mrfish#yoda ~]$ echo $?
0
[mrfish#yoda ~]$ ./u_exists.sh
missing username
[mrfish#yoda ~]$ echo $?
255
[mrfish#yoda ~]$ ./u_exists.sh aaa
no
[mrfish#indegy ~]$ echo $?
2

echo "$PASSWORD" | su -c "cd /" "$USER"
if [ "$?" = "0" ];then
echo "OK"
else
echo "Error"
fi

#!/bin/bash
read -p "Enter your Login Name: " loginname
home=`grep -w $loginname /etc/passwd | cut -ef:6 -d:`
if [ $home ]
echo "Exists"
else
echo "Not Exist"
fi

Related

Bash script create user

I'm trying to make a bash script that creates users in Ubuntu. If the user exist, then it should asks to put in a different username that does not exist.
The same I would like for creating groups. I hope you guys can help me!
if [ $(id -u) -eq 0 ]; then
read -p "Please enter a username: " username
# Check if user exist or not
egrep "^$username" /etc/passwd >/dev/null
while [ $? -eq 0 ]; do
read -p "User $username already exist! Please enter a different username: " username
exit 1
done
groupadd -f "${group}"
useradd -m -g "${group}" "${username}"
[ $? -eq 0 ] && echo "User added to system!" || echo "Could not create user!"
else
echo "Only root may add a user to the system."
exit 2
fi
Like this:
if ((UID!=0)); then
echo >&2 "Only root may add a user to the system."
exit 2
fi
read -p "Please enter a username: " username
# Check if user exist or not
if id "$username" &>/dev/null; then
echo >&2 "User $username already exist"
exit 1
fi
groupadd -f "$group"
if useradd -m -g "$group" "$username"; then
echo "User added to system!"
else
echo >&2 "Could not create user!"
exit 1
fi

How to look for user from input and create user if don't exist

I'm trying to create a shell script that ask for user input. If the user exist it lets you know; if the user doesn't exist it creates the user and password and adds them to a group. However, I am stuck and am hoping someone can assist. It seems to stop after it reads the response and doesn't execute the if/then
Here is what I have so far:
#!/bin/bash
echo "Which user would you like to use docker? "
read -r user
getent passwd "$user" > /dev/null 2&>1 && echo yes || echo no
read -r response
if [ "$response" == "yes" ];then
echo " User already exist"
if [ "$response" == "no" ];then
useradd -m $user
passwd $user
usermod -aG docker $user
fi
fi
You don't need to output yes or no; the if statement can test the exit status of getent just as && does.
echo "Which user would you like to use docker? "
IFS= read -r user
if getent passwd "$user" > /dev/null 2>&1; then
echo "User already exists"
else
useradd -m "$user" &&
passwd "$user" &&
usermod -aG docker "$user"
fi
Use a random password or also set a password like below, I guess the passwd command is the problem here for it expect a response in your example:
#!/bin/bash
group="docker"
password1="$(strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 8 | tr -d '\n';echo)"
read -p "Which user would you like to use docker: " user
grep -q ${user} /etc/passwd
# If grep command was true, we know user exist
if [[ "$?" = "0" ]];then
echo "${user} already exist"
else
# We can use 'read -p' instead of using echo + read
read -p "Add a password for ${user}: " password
# We can use -m and -G in same line
useradd -m ${user} -G ${group}
# Use read -p for set a password or use password1 for a random pass
chpasswd <<< ${user}:${password}
# Another way to add password without passwd
# echo ${user}:${password} | chpasswd
# Let us know user was added in group docker and with a password
echo "Successfully added ${user}/${group} and password has been set to ${password}......."
fi

Try/Except loop in shell [duplicate]

I have a script and want to ask the user for some information, but the script cannot continue until the user fills in this information. The following is my attempt at putting a command into a loop to achieve this but it doesn't work for some reason:
echo "Please change password"
while passwd
do
echo "Try again"
done
I have tried many variations of the while loop:
while `passwd`
while [[ "`passwd`" -gt 0 ]]
while [ `passwd` -ne 0 ]]
# ... And much more
But I can't seem to get it to work.
until passwd
do
echo "Try again"
done
or
while ! passwd
do
echo "Try again"
done
To elaborate on #Marc B's answer,
$ passwd
$ while [ $? -ne 0 ]; do !!; done
Is nice way of doing the same thing that's not command specific.
You need to test $? instead, which is the exit status of the previous command. passwd exits with 0 if everything worked ok, and non-zero if the passwd change failed (wrong password, password mismatch, etc...)
passwd
while [ $? -ne 0 ]; do
passwd
done
With your backtick version, you're comparing passwd's output, which would be stuff like Enter password and confirm password and the like.
If anyone looking to have retry limit:
max_retry=5
counter=0
until $command
do
sleep 1
[[ counter -eq $max_retry ]] && echo "Failed!" && exit 1
echo "Trying again. Try #$counter"
((counter++))
done
You can use an infinite loop to achieve this:
while true
do
read -p "Enter password" passwd
case "$passwd" in
<some good condition> ) break;;
esac
done
while [ -n $(passwd) ]; do
echo "Try again";
done;

How to add predefined users to a specific group in linux/bash script

I have been trying to implement a code that makes a predefined user created, be put into a specific groups (first 5 in MyMembers, next 5 in MyGroup, and last 5 to MyMinions), but I always got lost in coding it.
So far this is my code in creating predefined user.
#!/bin/bash
#This script adds a user with a hidden password to your #system.
ans=yes
while [[ "$ans" = yes ]] ;
do
if [ $(id -u) -eq 0 ];
then
read -p "Enter username: " username
read -s -p "Enter password: " password
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ];
then
echo "$username already exists!"
exit 1
else
pass=$(perl -e 'print crypt ($ARGV[0], "password")' $password)
useradd -m -p $pass $username
[ $? -eq 0 ] && echo -e "\nUser has been added to your system!" || echo "\nFailed to add the user!"
fi
else
echo "Only root may add a user to the system"
exit 2
fi
echo -e "\nDo you still want to add more users?. \nType yes to continue adding. \nType yes or any key to exit"
read ans
done
exit

How to check password in bash

Is it possible to check that user password is correct in bash script? If so please show me how. Thank you
This works for me:
#ensure sudo isn't saving a recent password
sudo -k
#prime it
echo $ROOTPASSWORD | sudo -S echo hello &> /dev/null
#test it
if ! [ "$(sudo -n echo hello 2>&1)" == "hello" ]; then
echo "Incorrect password was entered"
fi

Resources