I am writing a bash script to add users but I am stuck when adding users to groups.
What I have:
#--------------------------------------------------
#This First reads the users.csv file splits up the data
#Checks if the users exists and if not makes them and gives them a password.
#it will then
file="users.csv.1"
Count=0
while IFS=";"; read email birthDate group sharedFolder
do
echo -e "Email: $email"
firstCharacter=${email:0:1}
echo $firstCharacter
local_part="${email%%@*}"
last_Name="${local_part##*.}"
echo "$last_Name"
UserName="$firstCharacter$last_Name"
USERID="$UserName"
egrep -i "^${USERID}:" /etc/passwd
if [[ $? -eq 0 ]]; then
echo "User $USERID exists in etc/passwd"
else
echo "User $USERID does not exists in etc/passwd"
fi
sudo useradd $UserName
echo -e "UserName: $UserName"
echo -e "Password: $birthDate" | tr -d '/'
echo "$UserName:$birthDate" | sudo chpasswd
echo -e "Birth Date: $birthDate"
if [[ "$group" == "staff" ]]; then
usermod -a -G "$UserName" staff
elif [[ "$group" == "visitor" ]]; then
usermod -a -G "$UserName" visitor
elif [[ "$group" == "sudo" ]]; then
usermod -a -G "$UserName" sudo
else
echo -e "no group to add to"
fi
echo -e "Group: $group"
echo -e "shared Folder: $sharedFolder\n"
done < "$file"
My problem is that it will keep coming back and saying usermod: user 'staff' does not exist
I do make the groups at the start of the script. Shown here:
if [ $(getent group staff) ]; then
echo "group staff exists."
echo $'\n'
else
echo "group staff does NOT exsit."
echo "one will be created now"
sudo groupadd staff
echo "staff group has been created"
echo $'\n'
fi
if [ $(getent group visitor) ]; then
echo "group visitor exist."
echo $'\n'
else
echo "group visitor does Not exist."
echo "One will be created now"
sudo groupadd visitor
echo "visitor group has been created"
echo $'\n'
fi
I am not sure what I am doing wrong because I get the checks back at the start of the scripts saying that the groups exist.