Shell script keeps executing even if was true
I have a simple shell script to check if the user exist, if not, add that user
#!/usr/bin/bash
echo "Enter user"
read -r user
if [ "$(id -u "$user" &>/dev/null)" = 1 ]; then
echo "user existed"
else
useradd "$user"
echo "add password"
passwd "$user"
echo "$user" &>>text.txt
echo "saved"
fi
But it does not display the "echo user exist"
. instead it displays like so:
Enter user
abcdef
useradd: user 'abcdef' already exists
add password
New password:
In this case abcdef
is an existing user
Please let me know what goes wrong here, thanks a lot.
The following condition in your script:
if [ "$(id -u "$user" &>/dev/null)" = 1 ]; then
will never be true. It would be true only if the output of command id -u "$user" &>/dev/null
would be the single digit 1, but as any output from that command is redirected to /dev/null
, this will never happen.
Replace that line with
if { id -u "$user" &>/dev/null ; } then
This condition checks the exit status of the command (and not its output like $(...)
does) and will be true if the command id -u "$user" &>/dev/null
succeeds (that is, user exists) and false if it fails (that is, user doesn't exist).
The answer by @raj is 100% correct for simplifying code.
These are just some alternate ways of using the exit codes and maybe shedding a little more light in how they can be used.
The exit code can be checked by doing an echo $?
right after your command of id -u $user &>/dev/null
which doesn't need to be encased in $(..)
or anything like that.
Just try id -u <username> &>/dev/null
and then type in echo $?
to check the exit code.
Example:
terrance@terrance-ubuntu:~$ id -u terrance &>/dev/null
terrance@terrance-ubuntu:~$ echo $?
0
terrance@terrance-ubuntu:~$ id -u mark &>/dev/null
terrance@terrance-ubuntu:~$ echo $?
1
In the above example, the user mark
does not exist on my computer thus the exit status of 1.
Using the exit code you can put it into a case
statement instead of an if..else
statement.
#!/bin/bash
echo "Enter username"
read -r user
id -u "$user" &>/dev/null
case $? in
0) echo "User exists";;
1) adduser $user
echo "add password"
passwd $user
echo $user >> text.txt
echo "saved";;
esac
Interestingly enough, using an if [ ]; then
can still be used as well by adding an echo $?
into your if check, but I did notice that you were checking for 1 to be if exist, but 1 means that the code exited with 1 meaning not found.
Adding it will work like this as well.
#!/bin/bash
echo "Enter username"
read -r user
if [ $(id -u "$user" &>/dev/null; echo $?) == 0 ]; then
echo "User exists"
else
adduser $user
echo "add password"
passwd $user
echo $user >> text.txt
echo "saved"
fi