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
id -u testuser
and check if the result is 1. Because 1 is the only thing that will proceed toecho "User exists"
id
is redirected to/dev/null
.id -u $user &>/dev/null
useecho $?
and that will produce either a 0 or 1. 0 meaningexit code 0
or true, 1 meaningexit code 1
or false. Or you can haveif [[ $? == 0 ]]; then
, etc.id -u $user &>/dev/null
straight away as condition inif
.case
statements works very well. Theid -u
produces the user ID number and not a 1 or 0. So, outputtingid -u
to >/dev/null will get rid of the 1000 if that is the user ID.