Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if a user exists and create the user if the name is free?

I’m trying to create a user creator script, and I keep getting stuck. I just started learning bash shell scripting, so I’m not very good.
Here’s my script:

#!/bin/bash
clear
echo "Welcome to"
echo "USER CREATOR"
echo "How many user accounts would you like to create?"
read num
echo "What would you like the username prefix to be? (e.g. 'Student' (Student01, Student02, Student03...) or 'User' (User01, User02, User03...)"
read prefix

declare -i maxaccounts=0
declare -i accountnum=1
zero="0"

while [ $num -gt $maxaccounts ]
do
    if [ $accountnum -lt 10 ]
    then
        username=${prefix}${zero}${accountnum}
    else
        username=${prefix}${accountnum}
    fi

    if test -d /home/$username; then
        accountnum=$accountnum+1
        maxaccounts=$maxaccounts+1
    else
        useradd $username
        accountnum=$accountnum+1
        maxaccounts=$maxaccounts+1
    fi
done

Now, it CREATES the user accounts just fine… but for some reason I can’t figure out, it isn’t actually checking to see if the username exists AND skipping it if it does. What can I do?
(ALSO I’m using a Centos Virtual Machine for reference)

Here’s some of the other forums and sites I’ve looked at to try to figure out how to write this code:
superuser: find-out-if-user-name-exists

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

stackoverflow: check-whether-a-user-exists?

stackoverflow: bash-script-to-validate-the-existence-of-user-name-in-etc-passwd

stackoverflow: how-would-i-check-if-user-exists-in-a-bash-script-and-re-ask-for-new-user-if-use

sslhow: check-user-shell-in-linux

unix.stackexchange: check-if-user-exist-in-etc-passwd-if-exist-create-new-one-with-prefix

baeldung: user-exists-check

>Solution :

Like this:

if getent passwd username &>/dev/null; then
   echo 'username exists'
else
   do_something
fi

Or just:

getent passwd username &>/dev/null || do_something
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading