M M
M M

Reputation: 13

Create/delete users from text file using Bash script

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

        sudo useradd "$user_list" -m -p "$user_list"

        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.

Upvotes: 1

Views: 6349

Answers (2)

NikoS1987
NikoS1987

Reputation: 1

read -p 'add username: ' USER_NAME read -p 'add password: ' PASSWORD

useradd -m ${USER_NAME} echo ${PASSWORD} | passwd --stdin ${USER_NAME} exit 0

Upvotes: 0

ivanzg
ivanzg

Reputation: 527

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

Upvotes: 1

Related Questions