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
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
UPDATE
I figured it out. I added the `maxaccounts=$maxaccounts+1` variable to increase even when the account wasn't creating, so it was just skipping making new accounts because the code told it that it already made the accounts in the loop. Here's my final code:#!/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 id -u $username &>/dev/null; then
accountnum=$accountnum+1
else
useradd $username
accountnum=$accountnum+1
maxaccounts=$maxaccounts+1
fi
done