Please help me. I wanted to write a script to add users. It was supposed to work in such a way that after creating one user, it asks whether to create another. I also wanted to display that the user was added or not added. The script I have works, but there is one problem. If I create a user by entering the correct password, I get a message that "user has been added". If I enter the wrong username, I get a message that "Failed to add a user "$username" !". However, when I create a user and enter two different passwords, I get an error that the passwords do not match. I abort adding the user and then the script says "user has been added". How do I fix this error, so that the script serves - if i cancel adding user it will show "error". Thanks for any tips.
#!/bin/bash
count=0
while [ $count -le 10 ]
do
while true; do
read -p "Do you want to add a user ? (Y/n) " yn
case $yn in
[yY] ) read -p "Enter a username without sudo privileges : " username
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "User $username exists!"
else
adduser --gecos GECOS "$username"
usermod -aG sudo "$username"
[ $? -eq 0 ] && echo "user has been added." || echo "Failed to add a user "$username" !"
fi
break;;
[nN] ) echo -----------------------------------------------;
count=$((10));
break;;
* ) echo invalid response;;
esac
done
count=$((count+1))
done
correct display of the script's operation
Update.
When I add the user correctly, I get the information -
user has been added.
when I enter the wrong name, I get the information -
Failed to add a user "$username" !
when I enter the wrong passwords and cancel adding a user, I get:
user has been added.
I tried to remove adding to the group, but the result is as above.
#!/bin/bash
while true; do
read -p "Do you want to add a user ? (Y/n) " yn
case $yn in
[yY] ) read -p "Enter a username without sudo privileges : " username
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "User $username exists!"
else
adduser --gecos GECOS "$username"
[ $? -eq 0 ] && echo "user has been added." || echo "Failed to add a user "$username" !"
fi
break;;
[nN] ) echo -----------------------------------------------;
break;;
* ) echo invalid response;;
esac
done
I tried - adduser --gecos GECOS "$username" && usermod -aG sudo "$username" but when I cancel adding user it shows "user has been added.". I also removed usermod -aG sudo "$username" , and when I canceling adding a user it shows "user has been added." .
To start, I have already looked at the previous comments in the others listed here but unfortunately, none of the help provided has solved my issue.
I am working in CentOS 7 as my environment and I am coding some error handling into my add user script.
#! /bin/bash
echo -n "Enter username: "
read -r username
/bin/egrep -i "^${username}:" /etc/passwd
if [ $? -eq 0 ]
echo "User $username already exists. Please check the username and try again."
elif [ $? eq 1 ]
echo "User $username does not exist. Please proceed with account creation."
then
adduser "$username"
echo -n "Enter password: "
read -r -s password
echo $username:$password | chpasswd
touch /etc/sudoers.d/sugroup
chmod 0440 /etc/sudoers.d/sugroup
echo "$username ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sugroup
else
echo "Error encountered."
fi
When I go to test it, I get the following error message:
./testscript-error.sh line 7: syntax error near unexpected token 'elif'
./testscript-error.sh line 7: elif [ $? eq 1 ]
I've tried:
elif [ $? eq 1 ]**;**
echo "User $username does not exist. Please proceed with account creation."
then
adduser "$username"
echo -n "Enter password: "
read -r -s password
echo $username:$password | chpasswd
touch /etc/sudoers.d/sugroup
chmod 0440 /etc/sudoers.d/sugroup
echo "$username ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sugroup**;**
I've also tried:
elif [ $? eq 1 ]
then
echo "User $username does not exist. Please proceed with account creation."
then
adduser "$username"
echo -n "Enter password: "
read -r -s password
echo $username:$password | chpasswd
touch /etc/sudoers.d/sugroup
chmod 0440 /etc/sudoers.d/sugroup
echo "$username ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sugroup
Also with the same result. Not sure what I'm missing and could use another pair of eyes on it.
Here you go... I hope you will understand better the syntax and usage:
#!/bin/bash
while true; do
echo -n "Enter username: "
read -r username
/bin/egrep -i "^${username}:" /etc/passwd
if [ $? -eq 0 ]; then
echo "User $username already exists. Please check the username and try again."
else
echo "User $username does not exist. Proceed with account creation."
break
fi
done
adduser "$username"
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
echo -n "Enter password: "
read -r -s password
echo "$username:$password" | chpasswd
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
touch /etc/sudoers.d/sugroup
chmod 0440 /etc/sudoers.d/sugroup
echo "$username ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sugroup
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
Here is the finished working code.
#!/bin/bash
#========================================================================================================
# This script allows for account creation on a server |
# It also performs error handling to ensure that the user doesn't currently exist on the system. |
# Also provides feedback from the input to verify the entries are correct. |
#========================================================================================================
while true; do
echo -n "Enter username: "
read -r username
/bin/egrep -i "^${username}:" /etc/passwd
if [ $? -eq 0 ]; then
echo "User $username already exists. Please check the username and try again."
else
echo "User $username does not exist. Proceed with account creation."
break
fi
done
adduser "$username"
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
echo -n "Enter password: "
read -r -s password
echo "$username:$password" | chpasswd
echo "Password was succesfully set for $username."
if [ $? -gt 0 ]; then
echo "Error encountered. There was a problem with your entry. Please re-run the script and try again."
exit 1
fi
usermod -a -G wheel "$username"
echo "User was succesfully added to the group wheel."
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
echo "Successfully added $username to the system."
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
I'm getting the following error:
./adduser.sh: line 21: syntax error near unexpected token `else'
./adduser.sh: line 21: ` else'
I have been stuck here for an hour and I just can not figure it out.
#!/bin/bash
#==========================================================================================================================================
# Script Name: adduser.sh
# By: Tim mayo
# Date: 3/2013
# Purpose: Add a user to the Linux system
# Command line: adduser.sh
#
#==========================================================================================================================================
read -p "Enter username : " username
read -s -p "Enter password : " password
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p $pass $username
[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
fi
else
echo "Root user can only add a user to the Linux system"
exit 2
fi
The else keyword isn't associated with any if statement; you ended the if statement with the fi keyword on line 20. Perhaps you are missing an if just before the two read statements?
Another 'run as root only' example:
#!/bin/bash
if [ $UID -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 exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p $pass $username
[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
fi
else
echo "Root user can only add a user to the Linux system"
exit 2
fi
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