Bash Script - adduser - bash

Please help me. I wanted to write a script to add users. It was supposed to work in such a way that after creating one user, it asks whether to create another. I also wanted to display that the user was added or not added. The script I have works, but there is one problem. If I create a user by entering the correct password, I get a message that "user has been added". If I enter the wrong username, I get a message that "Failed to add a user "$username" !". However, when I create a user and enter two different passwords, I get an error that the passwords do not match. I abort adding the user and then the script says "user has been added". How do I fix this error, so that the script serves - if i cancel adding user it will show "error". Thanks for any tips.
#!/bin/bash
count=0
while [ $count -le 10 ]
do
while true; do
read -p "Do you want to add a user ? (Y/n) " yn
case $yn in
[yY] ) read -p "Enter a username without sudo privileges : " username
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "User $username exists!"
else
adduser --gecos GECOS "$username"
usermod -aG sudo "$username"
[ $? -eq 0 ] && echo "user has been added." || echo "Failed to add a user "$username" !"
fi
break;;
[nN] ) echo -----------------------------------------------;
count=$((10));
break;;
* ) echo invalid response;;
esac
done
count=$((count+1))
done
correct display of the script's operation
Update.
When I add the user correctly, I get the information -
user has been added.
when I enter the wrong name, I get the information -
Failed to add a user "$username" !
when I enter the wrong passwords and cancel adding a user, I get:
user has been added.
I tried to remove adding to the group, but the result is as above.
#!/bin/bash
while true; do
read -p "Do you want to add a user ? (Y/n) " yn
case $yn in
[yY] ) read -p "Enter a username without sudo privileges : " username
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "User $username exists!"
else
adduser --gecos GECOS "$username"
[ $? -eq 0 ] && echo "user has been added." || echo "Failed to add a user "$username" !"
fi
break;;
[nN] ) echo -----------------------------------------------;
break;;
* ) echo invalid response;;
esac
done

I tried - adduser --gecos GECOS "$username" && usermod -aG sudo "$username" but when I cancel adding user it shows "user has been added.". I also removed usermod -aG sudo "$username" , and when I canceling adding a user it shows "user has been added." .

Related

Bash script create user

I'm trying to make a bash script that creates users in Ubuntu. If the user exist, then it should asks to put in a different username that does not exist.
The same I would like for creating groups. I hope you guys can help me!
if [ $(id -u) -eq 0 ]; then
read -p "Please enter a username: " username
# Check if user exist or not
egrep "^$username" /etc/passwd >/dev/null
while [ $? -eq 0 ]; do
read -p "User $username already exist! Please enter a different username: " username
exit 1
done
groupadd -f "${group}"
useradd -m -g "${group}" "${username}"
[ $? -eq 0 ] && echo "User added to system!" || echo "Could not create user!"
else
echo "Only root may add a user to the system."
exit 2
fi
Like this:
if ((UID!=0)); then
echo >&2 "Only root may add a user to the system."
exit 2
fi
read -p "Please enter a username: " username
# Check if user exist or not
if id "$username" &>/dev/null; then
echo >&2 "User $username already exist"
exit 1
fi
groupadd -f "$group"
if useradd -m -g "$group" "$username"; then
echo "User added to system!"
else
echo >&2 "Could not create user!"
exit 1
fi

How to look for user from input and create user if don't exist

I'm trying to create a shell script that ask for user input. If the user exist it lets you know; if the user doesn't exist it creates the user and password and adds them to a group. However, I am stuck and am hoping someone can assist. It seems to stop after it reads the response and doesn't execute the if/then
Here is what I have so far:
#!/bin/bash
echo "Which user would you like to use docker? "
read -r user
getent passwd "$user" > /dev/null 2&>1 && echo yes || echo no
read -r response
if [ "$response" == "yes" ];then
echo " User already exist"
if [ "$response" == "no" ];then
useradd -m $user
passwd $user
usermod -aG docker $user
fi
fi
You don't need to output yes or no; the if statement can test the exit status of getent just as && does.
echo "Which user would you like to use docker? "
IFS= read -r user
if getent passwd "$user" > /dev/null 2>&1; then
echo "User already exists"
else
useradd -m "$user" &&
passwd "$user" &&
usermod -aG docker "$user"
fi
Use a random password or also set a password like below, I guess the passwd command is the problem here for it expect a response in your example:
#!/bin/bash
group="docker"
password1="$(strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 8 | tr -d '\n';echo)"
read -p "Which user would you like to use docker: " user
grep -q ${user} /etc/passwd
# If grep command was true, we know user exist
if [[ "$?" = "0" ]];then
echo "${user} already exist"
else
# We can use 'read -p' instead of using echo + read
read -p "Add a password for ${user}: " password
# We can use -m and -G in same line
useradd -m ${user} -G ${group}
# Use read -p for set a password or use password1 for a random pass
chpasswd <<< ${user}:${password}
# Another way to add password without passwd
# echo ${user}:${password} | chpasswd
# Let us know user was added in group docker and with a password
echo "Successfully added ${user}/${group} and password has been set to ${password}......."
fi

Syntax error near unexpected token `elif' - Already read other posts

To start, I have already looked at the previous comments in the others listed here but unfortunately, none of the help provided has solved my issue.
I am working in CentOS 7 as my environment and I am coding some error handling into my add user script.
#! /bin/bash
echo -n "Enter username: "
read -r username
/bin/egrep -i "^${username}:" /etc/passwd
if [ $? -eq 0 ]
echo "User $username already exists. Please check the username and try again."
elif [ $? eq 1 ]
echo "User $username does not exist. Please proceed with account creation."
then
adduser "$username"
echo -n "Enter password: "
read -r -s password
echo $username:$password | chpasswd
touch /etc/sudoers.d/sugroup
chmod 0440 /etc/sudoers.d/sugroup
echo "$username ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sugroup
else
echo "Error encountered."
fi
When I go to test it, I get the following error message:
./testscript-error.sh line 7: syntax error near unexpected token 'elif'
./testscript-error.sh line 7: elif [ $? eq 1 ]
I've tried:
elif [ $? eq 1 ]**;**
echo "User $username does not exist. Please proceed with account creation."
then
adduser "$username"
echo -n "Enter password: "
read -r -s password
echo $username:$password | chpasswd
touch /etc/sudoers.d/sugroup
chmod 0440 /etc/sudoers.d/sugroup
echo "$username ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sugroup**;**
I've also tried:
elif [ $? eq 1 ]
then
echo "User $username does not exist. Please proceed with account creation."
then
adduser "$username"
echo -n "Enter password: "
read -r -s password
echo $username:$password | chpasswd
touch /etc/sudoers.d/sugroup
chmod 0440 /etc/sudoers.d/sugroup
echo "$username ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sugroup
Also with the same result. Not sure what I'm missing and could use another pair of eyes on it.
Here you go... I hope you will understand better the syntax and usage:
#!/bin/bash
while true; do
echo -n "Enter username: "
read -r username
/bin/egrep -i "^${username}:" /etc/passwd
if [ $? -eq 0 ]; then
echo "User $username already exists. Please check the username and try again."
else
echo "User $username does not exist. Proceed with account creation."
break
fi
done
adduser "$username"
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
echo -n "Enter password: "
read -r -s password
echo "$username:$password" | chpasswd
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
touch /etc/sudoers.d/sugroup
chmod 0440 /etc/sudoers.d/sugroup
echo "$username ALL=(ALL) NOPASSWD: ALL" >> /etc/sudoers.d/sugroup
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
Here is the finished working code.
#!/bin/bash
#========================================================================================================
# This script allows for account creation on a server |
# It also performs error handling to ensure that the user doesn't currently exist on the system. |
# Also provides feedback from the input to verify the entries are correct. |
#========================================================================================================
while true; do
echo -n "Enter username: "
read -r username
/bin/egrep -i "^${username}:" /etc/passwd
if [ $? -eq 0 ]; then
echo "User $username already exists. Please check the username and try again."
else
echo "User $username does not exist. Proceed with account creation."
break
fi
done
adduser "$username"
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
echo -n "Enter password: "
read -r -s password
echo "$username:$password" | chpasswd
echo "Password was succesfully set for $username."
if [ $? -gt 0 ]; then
echo "Error encountered. There was a problem with your entry. Please re-run the script and try again."
exit 1
fi
usermod -a -G wheel "$username"
echo "User was succesfully added to the group wheel."
if [ $? -gt 0 ]; then
echo "Error encountered."
exit 1
fi
echo "Successfully added $username to the system."

How to add predefined users to a specific group in linux/bash script

I have been trying to implement a code that makes a predefined user created, be put into a specific groups (first 5 in MyMembers, next 5 in MyGroup, and last 5 to MyMinions), but I always got lost in coding it.
So far this is my code in creating predefined user.
#!/bin/bash
#This script adds a user with a hidden password to your #system.
ans=yes
while [[ "$ans" = yes ]] ;
do
if [ $(id -u) -eq 0 ];
then
read -p "Enter username: " username
read -s -p "Enter password: " password
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ];
then
echo "$username already exists!"
exit 1
else
pass=$(perl -e 'print crypt ($ARGV[0], "password")' $password)
useradd -m -p $pass $username
[ $? -eq 0 ] && echo -e "\nUser has been added to your system!" || echo "\nFailed to add the user!"
fi
else
echo "Only root may add a user to the system"
exit 2
fi
echo -e "\nDo you still want to add more users?. \nType yes to continue adding. \nType yes or any key to exit"
read ans
done
exit

New User creation script error

I have the script listed below that I can't seem to get the issue worked out of. I'm trying to make an interactive login script for a UNIX class that I'm in. I'm basically building out a command to pass into useradd. The command that I make when passed into the command line (while adding sudo) works as expected, but when I try to run it from my script (which is generating the text that I copy/paste into the command line) it gives me some errors... At this point I'm at a loss for what to try next to resolve the issue.
ERROR:
useradd -m --user-group jaredm2 #command that is attempting to run...
useradd: invalid option -- ' '
Usage: useradd [options] LOGIN
....rest of useradd error text....
SCRIPT:
#!/bin/bash
#Add a new user
FINALCOMMAND="-m"
#import useradd defaults...
. /etc/default/useradd
#Check if running as root
if [ "$(id -u)" != "0" ]; then
echo "This script must be ran as root"
exit 1
fi
#Get the new users Name
#echo -n "Please enter the users First and Last Name and press [ENTER]: "
#read Name
#Get the new users username
echo "The username must be 4-20 characters."
echo -n "Please enter the users requested username and press [ENTER]: "
read USERNAME
while [ $(grep -c "^${USERNAME}:" /etc/passwd) -ge 1 ] || [ ${#USERNAME} -le 3 ] || [ ${#USERNAME} -ge 21 ]
do
echo " "
echo "Error: Username is in use or invalid. Please select a different username."
echo " "
echo -n "Please enter the users requested username and press [ENTER]: "
read USERNAME
done #USERNAME will be valid from this point
#ASK about the default shell now
echo -n "Enter the new shell if you would like one (currently $SHELL) or leave blank for the default and press [ENTER]: "
read tempSHELL
if [ ${#tempSHELL} -ge 1 ]; then
SHELL="$tempSHELL"
FINALCOMMAND="$FINALCOMMAND ""-s $SHELL"
fi
#ASK about a different primary group
echo "Would you like to enter a non-default primary user group? Defaults to creating a new group that matches the username"
echo "Enter a new Primary Group or leave blank for the default and press [ENTER]: "
read newPrimaryGroup
if [ ${#newPrimaryGroup} -eq 0 ]; then
FINALCOMMAND="$FINALCOMMAND --user-group"
else
if [ $(grep -c "^${newPrimaryGroup}" /etc/group) -ge 1 ]; then
FINALCOMMAND="$FINALCOMMAND -g $newPrimaryGroup"
else
echo "Invalid group specified reverting to default!"
FINALCOMMAND="$FINALCOMMAND --user-group"
fi
fi
useradd -m --user-group jaredm2
#ASK about additional groups
echo "Would you like the new user to be a part of any additional groups? Leave blank if no additional groups are needed or enter additional groups in the format of GROUP1,GROUP2,... (NO SPACES) and press [ENTER]: "
read extraGroups
#remove spaces if the user entered any
extraGroups="${extraGroups//[[:space:]]}"
FINALEXTRAGROUPS=""
IFS=","
for g in $extraGroups
do
if [ $(grep -c "^${g}" /etc/group) -ge 1 ]; then
FINALEXTRAGROUPS="$FINALEXTRAGROUPS,$g"
else
echo "$g is invalid user will not be added..."
fi
done
FINALEXTRAGROUPS=$(echo "$FINALEXTRAGROUPS" | tail -c +2)
if [ ${#FINALEXTRAGROUPS} -ge 1 ]; then
FINALCOMMAND="$FINALCOMMAND -G $FINALEXTRAGROUPS"
fi
#ASK about the home directory
echo "Would you like to enter a new home directory for the user? Leave blank to use the default of $HOME/$USERNAME or enter your own and press [ENTER]: "
read NEWHOME
if [ ${#NEWHOME} -ge 1 ]; then
FINALCOMMAND="$FINALCOMMAND -d $NEWHOME"
fi
#ADD the username to the command
FINALCOMMAND=`echo "$FINALCOMMAND $USERNAME" | sed 's/ *$//g' | sed 's/^ *//g'`
echo "useradd $FINALCOMMAND"
#PASSCOMMAND="sudo passwd $USERNAME"
#ADD THE USER
`useradd $FINALCOMMAND`
`passwd $USERNAME`
`chfn $USERNAME`
UPDATE: ADDED DEBUG CONTENT
+ '[' 0 -ge 1 ']'
++ sed 's/^ *//g'
++ sed 's/ *$//g'
++ echo '/usr/sbin/useradd -m -U JaredM'
+ FINALCOMMAND='/usr/sbin/useradd -m -U JaredM'
++ '/usr/sbin/useradd -m -U JaredM'
./addnewuser.sh: line 89: /usr/sbin/useradd -m -U JaredM: No such file or directory
By using arrays you could prevent IFS related errors in the command-line and it's a lot cleaner. This one's already tested. I made some clean-ups to the code as well.
#!/bin/bash
#Add a new user
FINALCOMMAND=("-m")
#Import useradd defaults...
. /etc/default/useradd
#Check if running as root
if [ "$(id -u)" != "0" ]; then
echo "This script must be ran as root"
exit 1
fi
#Get the new users Name
#echo -n "Please enter the users First and Last Name and press [ENTER]: "
#read Name
#Get the new users username
echo "The username must be 4-20 characters."
echo -n "Please enter the users requested username and press [ENTER]: "
read USERNAME
while [ $(grep -c "^${USERNAME}:" /etc/passwd) -ge 1 ] || [ ${#USERNAME} -le 3 ] || [ ${#USERNAME} -ge 21 ]; do
echo " "
echo "Error: Username is in use or invalid. Please select a different username."
echo " "
echo -n "Please enter the users requested username and press [ENTER]: "
read USERNAME
done #USERNAME will be valid from this point
#ASK about the default shell now
echo -n "Enter the new shell if you would like one (currently $SHELL) or leave blank for the default and press [ENTER]: "
read tempSHELL
if [ ${#tempSHELL} -ge 1 ]; then
SHELL="$tempSHELL"
FINALCOMMAND=("${FINALCOMMAND[#]}" "-s" "$SHELL")
fi
#ASK about a different primary group
echo "Would you like to enter a non-default primary user group? Defaults to creating a new group that matches the username"
echo -n "Enter a new Primary Group or leave blank for the default and press [ENTER]: "
read newPrimaryGroup
if [ ${#newPrimaryGroup} -eq 0 ]; then
FINALCOMMAND=("${FINALCOMMAND[#]}" "--user-group")
else
if [ $(grep -c "^${newPrimaryGroup}" /etc/group) -ge 1 ]; then
FINALCOMMAND=("${FINALCOMMAND[#]}" "-g" "$newPrimaryGroup")
else
echo "Invalid group specified reverting to default!"
FINALCOMMAND=("${FINALCOMMAND[#]}" "--user-group")
fi
fi
#ASK about additional groups
echo -n "Would you like the new user to be a part of any additional groups? Leave blank if no additional groups are needed or enter additional groups in the format of GROUP1,GROUP2,... (NO SPACES) and press [ENTER]: "
read extraGroups
#remove spaces if the user entered any
extraGroups="${extraGroups//[[:space:]]}"
FINALEXTRAGROUPS=''
IFS=, read -a TEMP <<< "$extraGroups"
for g in "${TEMP[#]}"; do
if [ $(grep -c "^${g}" /etc/group) -ge 1 ]; then
FINALEXTRAGROUPS="$FINALEXTRAGROUPS,$g"
else
echo "$g is invalid user will not be added..."
fi
done
if [ ${#FINALEXTRAGROUPS[#]} -ge 1 ]; then
FINALCOMMAND=("${FINALCOMMAND[#]}" "-G" "${FINALEXTRAGROUPS:1}")
fi
#ASK about the home directory
echo -n "Would you like to enter a new home directory for the user? Leave blank to use the default of $HOME/$USERNAME or enter your own and press [ENTER]: "
read NEWHOME
if [ ${#NEWHOME} -ge 1 ]; then
FINALCOMMAND=("${FINALCOMMAND[#]}" "-d" "$NEWHOME")
fi
#ADD the username to the command
FINALCOMMAND=("${FINALCOMMAND[#]}" "$USERNAME")
#PASSCOMMAND="sudo passwd $USERNAME"
#ADD THE USER
echo "useradd ${FINALCOMMAND[#]}"
useradd "${FINALCOMMAND[#]}"
passwd "$USERNAME"
chfn "$USERNAME"
Note: In newer versions of bash you could just use += to append a value to an array e.g. ARRAY+=("value")
Also by my additional preferences I would improve the code further this way, but that's not the best of it yet:
#!/bin/bash
shopt -s extglob
# Check if running as root.
if [[ "$(id -u)" != 0 ]]; then
echo "This script must be ran as root."
exit 1
fi
# Initialize useradd command variable.
USERADDCOMMAND=("useradd" "-m")
# Import useradd defaults.
. /etc/default/useradd
# Get the new user's name.
#echo -n "Please enter the users First and Last Name and press [ENTER]: "
#read NAME
# Get the new users username.
echo "The username must be 4-20 characters."
while :; do
read -p "Please enter the user's requested username and press [ENTER]: " USERNAME
[[ ${#USERNAME} -ge 4 && ${#USERNAME} -le 20 && $USERNAME == +([[:alpha:]])*([[:alnum:]_-]) ]] || {
echo "Error: Username is invalid. Please enter a different username."
continue
}
[[ $(grep -c "^${USERNAME}:" /etc/passwd) -ge 1 ]] && {
echo "Error: Username is in use. Please enter a different username."
continue
}
break
done
# Ask about the default shell.
read -p "Enter the new shell if you would like one (currently $SHELL) or leave blank for the default and press [ENTER]: " SHELL_
if [[ ${#SHELL_} -ge 1 ]]; then
USERADDCOMMAND=("${USERADDCOMMAND[#]}" "-s" "$SHELL_")
else
# We use this if we really are to use SHELL specified in $SHELL but it still needs further workarounds like checking if $SHELL is valid. Those could be easily done but it depends if this one's really necessary.
#USERADDCOMMAND=("${USERADDCOMMAND[#]}" "-s" "$SHELL")
:
fi
# Ask about a different primary group.
echo "Would you like to enter a non-default primary user group? Defaults to creating a new group that matches the username."
echo -n "Enter a new Primary Group or leave blank for the default and press [ENTER]: "
read NEWPRIMARYGROUP
if [[ ${#NEWPRIMARYGROUP} -eq 0 ]]; then
USERADDCOMMAND=("${USERADDCOMMAND[#]}" "--user-group")
else
if [[ $(grep -c "^${NEWPRIMARYGROUP}" /etc/group) -ge 1 ]]; then
USERADDCOMMAND=("${USERADDCOMMAND[#]}" "-g" "$NEWPRIMARYGROUP")
else
echo "Invalid group specified reverting to default!"
USERADDCOMMAND=("${USERADDCOMMAND[#]}" "--user-group")
fi
fi
# Ask about additional groups.
echo -n "Would you like the new user to be a part of any additional groups? Leave blank if no additional groups are needed or enter additional groups in the format of GROUP1,GROUP2,... (NO SPACES) and press [ENTER]: "
read EXTRAGROUPS
# Remove spaces if the user entered any.
EXTRAGROUPS="${EXTRAGROUPS//[[:space:]]}"
FINALEXTRAGROUPS=''
IFS=, read -a TEMP <<< "$EXTRAGROUPS"
for G in "${TEMP[#]}"; do
if [[ $(grep -c "^${g}" /etc/group) -ge 1 ]]; then
FINALEXTRAGROUPS="$FINALEXTRAGROUPS,$G"
else
echo "$G is an invalid user and will not be added."
fi
done
if [[ ${#FINALEXTRAGROUPS[#]} -ge 1 ]]; then
USERADDCOMMAND=("${USERADDCOMMAND[#]}" "-G" "${FINALEXTRAGROUPS:1}")
fi
# Ask about the home directory
read -p "Would you like to enter a new home directory for the user? Leave blank to use the default of $HOME/$USERNAME or enter your own and press [ENTER]: " NEWHOME
if [[ ${#NEWHOME} -ge 1 ]]; then
USERADDCOMMAND=("${USERADDCOMMAND[#]}" "-d" "$NEWHOME")
fi
# Add the username to the command
USERADDCOMMAND=("${USERADDCOMMAND[#]}" "$USERNAME")
# Add THE USER
echo "> ${USERADDCOMMAND[*]}"
"${USERADDCOMMAND[#]}"
echo "> passwd $USERNAME"
passwd "$USERNAME"
echo "> chfn $USERNAME"
chfn "$USERNAME" # -f "$NAME"
If the man -s8 useradd does not mention --user-group option available to use, then -U will not work. There's still another solution worth trying:
The default behavior (if the -g, -N, and -U options are not specified)
is defined by the USERGROUPS_ENAB variable in /etc/login.defs.
Another way is, you have to chain the useradd command with a groupadd command with the same username supplied as parameters to both the commands.
EDIT:
This must work. First create the group and then create the user and add this new user to the group. Since, you are doing this in a script this should do the job very well.
Do this:
groupadd jaredm2
useradd -m -g jaredm2 jaredm2
Instead of this:
useradd -m --user-group jaredm2
Note that certain other programs which would've been installed in your OS, may have changed your binary or access to it or even created an alias for it. Your which output suggests that it is linked to the useradd binary in bin directory, precisely where it should be.
So I guess:
the binary might have been changed or replaced by a process, by package installers or something else
there's some mismatch between the binary version and the man page version(most likely if you have upgraded your OS improperly, at some point of time)
I think, the only solutions would be using the above pair of commands or changing the useradd binary you are using manually.
The problem is caused by your script you made ​​the use magic quotes `...` to execute your shell commands.
These quotes should only be used if you want to store the return of a command in a variable:
example the instruction below:
FINALCOMMAND=`echo "$FINALCOMMAND $USERNAME" | sed 's/ *$//g' | sed 's/^ *//g'`
Otherwise it is not necessary to use this quote and they can produce bugs like yours.
you can put in your script:
useradd $FINALCOMMAND
passwd $USERNAME
chfn $USERNAME
instead of:
`useradd $FINALCOMMAND`
`passwd $USERNAME`
`chfn $USERNAME`
Judging from your update with debug content, it seems like what you are doing is different from the script you posted.
Anyway, from the debug output, I suspect you're trying to run the adduser command using double quotes
"$FINALCOMMAND"
or maybe enclosed in backticks too, as that seems to be the only situation that triggers the "No such file or directory" error message.
Getting rid of the double quotes should fix the problem.
p/s: Don't use command substitution (``) unless you're actually using the output (e.g. for testing or assigning to variables), or else something like this might happen
$ `echo Just saying hi`
Just: command not found
I fixed the bug in your script, simply remove the line IFS=","
It is a misuse of the environment variable IFS (Internal Field Separator)
The script becomes:
#!/bin/bash
#Add a new user
FINALCOMMAND="-m"
#import useradd defaults...
. /etc/default/useradd
#Check if running as root
if [ "$(id -u)" != "0" ]; then
echo "This script must be ran as root"
exit 1
fi
#Get the new users Name
#echo -n "Please enter the users First and Last Name and press [ENTER]: "
#read Name
#Get the new users username
echo "The username must be 4-20 characters."
echo -n "Please enter the users requested username and press [ENTER]: "
read USERNAME
while [ $(grep -c "^${USERNAME}:" /etc/passwd) -ge 1 ] || [ ${#USERNAME} -le 3 ] || [ ${#USERNAME} -ge 21 ]
do
echo " "
echo "Error: Username is in use or invalid. Please select a different username."
echo " "
echo -n "Please enter the users requested username and press [ENTER]: "
read USERNAME
done #USERNAME will be valid from this point
#ASK about the default shell now
echo -n "Enter the new shell if you would like one (currently $SHELL) or leave blank for the default and press [ENTER]: "
read tempSHELL
if [ ${#tempSHELL} -ge 1 ]; then
SHELL="$tempSHELL"
FINALCOMMAND="$FINALCOMMAND ""-s $SHELL"
fi
#ASK about a different primary group
echo "Would you like to enter a non-default primary user group? Defaults to creating a new group that matches the username"
echo "Enter a new Primary Group or leave blank for the default and press [ENTER]: "
read newPrimaryGroup
if [ ${#newPrimaryGroup} -eq 0 ]; then
FINALCOMMAND="$FINALCOMMAND --user-group"
else
if [ $(grep -c "^${newPrimaryGroup}" /etc/group) -ge 1 ]; then
FINALCOMMAND="$FINALCOMMAND -g $newPrimaryGroup"
else
echo "Invalid group specified reverting to default!"
FINALCOMMAND="$FINALCOMMAND --user-group"
fi
fi
#useradd -m --user-group jaredm2
#ASK about additional groups
echo "Would you like the new user to be a part of any additional groups? Leave blank if no additional groups are needed or enter additional groups in the format of GROUP1,GROUP2,... (NO SPACES) and press [ENTER]: "
read extraGroups
#remove spaces if the user entered any
extraGroups="${extraGroups//[[:space:]]}"
FINALEXTRAGROUPS=""
#IFS=","
for g in $extraGroups
do
if [ $(grep -c "^${g}" /etc/group) -ge 1 ]; then
FINALEXTRAGROUPS="$FINALEXTRAGROUPS,$g"
else
echo "$g is invalid user will not be added..."
fi
done
FINALEXTRAGROUPS=$(echo "$FINALEXTRAGROUPS" | tail -c +2)
if [ ${#FINALEXTRAGROUPS} -ge 1 ]; then
FINALCOMMAND="$FINALCOMMAND -G $FINALEXTRAGROUPS"
fi
#ASK about the home directory
echo "Would you like to enter a new home directory for the user? Leave blank to use the default of $HOME/$USERNAME or enter your own and press [ENTER]: "
read NEWHOME
if [ ${#NEWHOME} -ge 1 ]; then
FINALCOMMAND="$FINALCOMMAND -d $NEWHOME"
fi
#ADD the username to the command
FINALCOMMAND=`echo "$FINALCOMMAND $USERNAME" | sed 's/ *$//g' | sed 's/^ *//g'`
echo "useradd $FINALCOMMAND"
#PASSCOMMAND="sudo passwd $USERNAME"
#ADD THE USER
useradd $FINALCOMMAND
passwd $USERNAME
chfn $USERNAME

Resources