M M M M - 19 days ago 6
Linux Question

Bash Script - Create/delete users from text file

I know this question has been asked a lot but I just can't seem to get it working and I'm kinda on the clock, okay so.

I'm trying to make a bash script with a 4 option menu:
1 Add single user
2 Add from list
3 Delete single user
4 Delete from list

Adding and deleting single users I've got working it's just from list that keep defeating me.

This is the code I've got so far

#!/bin/bash

choice=5
# Main display
echo "Enter number to select an option"
echo
echo "1) Add Single User"
echo "2) Add Users from list"
echo "3) Delete Single User"
echo "4) Delete users from list"
echo


while [ $choice -eq 5 ]; do


read choice

if [ $choice -eq 1 ] ; then


echo -e "Enter Username"
read user_name
echo -e "Enter Password"
read user_passwd
sudo useradd $user_name -m -p $user_passwd
cat /etc/passwd

else

if [ $choice -eq 2 ] ; then
x=0
created=0

echo -e "Enter file name for users:"
read user_list
#for users in $user_list
#do
sudo useradd "$user_list" -m -p "$user_list"
#if [ $? -eq 0 ]
#then
# let created=$created+1
# fi

#done
else

if [ $choice -eq 3 ] ; then
cat /etc/passwd
echo
echo -e "User to be deleted:"
read del_user
sudo userdel -r $del_user
cat /etc/passwd
echo

else

if [ $choice -eq 4 ] ; then
echo "Not yet finished"


else
echo "#####################"
echo "# Stop being a noob #"
echo "#####################"
echo "1) Add Single User"
echo "2) Add Users from list"
echo "3) Delete Single User"
echo "4) Delete users from list"
echo
choice=5
fi
fi
fi
fi
done


The file to get the users from is just

User20
User19
User18
User17
User16
User15
User14
User13
User12
User11
User10
User9
User8
User7
User6
User5
User4
User3
User2
User1


It's sloppy as hell I know but I just need it for a demo from a presentation assignment, any help is appreciated.

Thanks.

Answer

After you read in the name of the file you have to iterate through that file and create or delete user for each line of the file.

Example :

for user in `cat user_list`
do
    sudo useradd "$user" -m -p "$user"
done