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