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
I'm writing a bash script to stop start my postgres DB service. Initially I succeeded in creating one, but as soon I enabled SSL certificate it prompts to enter the phrase password.
I know the easiest solution is to use expect , but in my environment i am not authorized to use it.
Can someone help me out in scripting as to how can I supply the PEM PHRASE password without a user intervention.
This is what I have worked so far.
-bash-4.2$ cat start_postgres_db.sh
cd `dirname $0`
. `dirname $0`/parameter.env
${POSTGREBIN}/pg_ctl -D ${POSTGREDATAPATH} start -w
while true
do
sleep 1
loopcnt=0
loopcnt=`expr ${loopcnt} + 1`
PRCCNT=`ps -ef | grep ${DBEXENAME} | grep -v grep|wc -l`
if [ ${PRCCNT} -eq 1 ]
then
echo "PostgreSQL process started sucessfully"
exit
fi
if [ ${loopcnt} -gt 11 ]
then
echo "PostgreSQL process not started successfully"
echo "su to postgres and run ${POSTGREBIN}/pg_ctl -D ${POSTGREDATAPATH} restart"
exit
fi
done
Execution:
bash-4.2$ ./start_postgres_db.sh
waiting for server to start....Enter PEM pass phrase:.........
You can provide a password to pg_ctl as argument on the command line with the option -P. I will assume it is contained in the variable ${POSTGREPASSWORD}.
start_postgres_db.sh
cd `dirname $0`
. `dirname $0`/parameter.env
${POSTGREBIN}/pg_ctl start -w -D ${POSTGREDATAPATH} -P ${POSTGREPASSWORD}
while true; do
sleep 1
(( loopcnt++ ))
PRCCNT=$(ps -ef | grep ${DBEXENAME} | grep -v grep | wc -l)
if [ ${PRCCNT} -eq 1 ]; then
echo "PostgreSQL process started sucessfully"
exit 0
fi
if [ ${loopcnt} -gt 11 ]; then
echo "PostgreSQL process not started successfully"
echo "su to postgres and run ${POSTGREBIN}/pg_ctl -D ${POSTGREDATAPATH} restart"
exit 1
fi
done
Im trying to do a shell script to add and delete users to a text file.
I want to use the args to compare if delete or add user, but no matter what args I put, both codes run, this is my code:
#!/bin/bash
arg1="$1"
arg2="$2"
if [ "$arg1"="add" ]; then
if ! grep -q $arg2 "users.txt"; then
sed -i -e 's/users:/users: \n - '$arg2'/g' users.txt
echo "user added: $arg2"
else
echo "user exists: $arg2"
fi
fi
if [ "$arg1"="del" ]; then
if grep -q $arg2 "users.txt"; then
sed -i -e 's/- '$arg2'//g' users.txt
echo "user $arg2 deleted"
else
echo "not found $arg2"
fi
fi
This is my text file users.txt:
users:
- angel
- rick
Running sh addUser.sh add user1 on terminal:
user added: user1
user user1 deleted
Running sh addUser.sh del user1 on terminal:
user added: user1
user user1 deleted
The result is the same, how can I fix it?
Thanks to #melpomene for the advice
The problem was the spaces in [ "$arg1"="add" ]
Change [ "$arg1"="add" ] to [ "$arg1" = "add" ] and it works perfectly.
#!/bin/bash
arg1="$1"
arg2="$2"
if [ "$arg1" = "add" ]; then
if ! grep -q $arg2 "users.txt"; then
sed -i -e 's/users:/users: \n - '$arg2'/g' users.txt
echo "user added: $arg2"
else
echo "user exists: $arg2"
fi
fi
if [ "$arg1" = "del" ]; then
if grep -q $arg2 "users.txt"; then
sed -i -e 's/- '$arg2'//g' users.txt
echo "user $arg2 deleted"
else
echo "not found $arg2"
fi
fi
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 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