Saturday, February 24, 2024
 Popular · Latest · Hot · Upcoming
rated 0 times [  9] [ 0]  / answers: 1 / hits: 920  / 2 Years ago, tue, july 12, 2022, 12:27:14

I have a simple shell script to check if the user exist, if not, add that user

echo "Enter user"
read -r user
if [ "$(id -u "$user" &>/dev/null)" = 1 ]; then
echo "user existed"
useradd "$user"
echo "add password"
passwd "$user"
echo "$user" &>>text.txt
echo "saved"

But it does not display the "echo user exist". instead it displays like so:

Enter user


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.

More From » scripts


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).

[#1237] Tuesday, July 12, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.

Total Points: 20
Total Questions: 109
Total Answers: 98

Location: Aruba
Member since Fri, Jun 24, 2022
2 Years ago
overine questions
Wed, Jan 11, 23, 02:15, 1 Year ago
Tue, Aug 10, 21, 01:39, 3 Years ago
Sun, Aug 22, 21, 20:50, 3 Years ago