LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Add multiple users on linux via file. (https://www.linuxquestions.org/questions/linux-newbie-8/add-multiple-users-on-linux-via-file-4175512720/)

NerdGZ 07-30-2014 05:39 AM

Add multiple users on linux via file.
 
Hello Everyone,

i created a script to add user automatically, and i wanted to difine the option separate with : or ;

As a default on my script i have it with space.

see the script:

#! /bin/bash

NEW_USERS="/home/nerd/userlist.txt"
HOME_BASE="/home/"

cat ${NEW_USERS} | \
while read USER GROUP COMMENT PASSWORD ;

do
useradd -c ${COMMENT} -G ${GROUP} -m -d ${HOME_BASE}${USER} ${USER}
echo $USER
echo $PASSWORD | passwd $USER --stdin
echo; echo "User $USER password change!"
chage -d 0 $USER
done

THIS is the userlist.txt

es666d group1 Nerd-GZ init1234


i would like to user the option Nerd-GZ without -
On the script is not possible because the option are only allow to be separate with space.

i think is something with the option on the script:

while read USER GROUP COMMENT PASSWORD

Could you please help me with that?

Thank you.
Nerd

Firerat 07-30-2014 06:12 AM

Sure

Code:

#! /bin/bash

NEW_USERS="/home/nerd/userlist.txt"
HOME_BASE="/home/"

while IFS="," read USER GROUP COMMENT PASSWORD;do
    useradd -c "${COMMENT}" -G ${GROUP} -m -d ${HOME_BASE}${USER} ${USER}
    echo $USER
    echo $PASSWORD | passwd $USER --stdin
    echo; echo "User $USER password change!"
    chage -d 0 $USER
done < "$NEW_USERS"

in your input file use "," instead of " " to separate the fields
the IFS="," is making the while read use , as the Input Field Separator
To protect from wordsplitting, wrap the field which contains a space with ""

Your input file would look like this

Code:

es666d,group1,Nerd GZ,init1234

NerdGZ 07-30-2014 06:35 AM

Hi Firerat,

Thank you very much. It is working!!!

Firerat 07-30-2014 06:49 AM

Glad to read it :)

The important thing is to understand *why* it works ;)


I should also comment on a couple of other things with your script.

Currently you are using CAPITALS for the variables, not a real problem but should be avoided
The reason: "System wide" varailbles are in CAPS, and you want to avoid mixing them up
For example,
Code:

echo $USER
Notice that I also used "heredocs" to get the input file instead of using cat.


Some links to help you out

http://www.tldp.org/LDP/Bash-Beginners-Guide/html/
http://www.tldp.org/LDP/abs/html/
http://mywiki.wooledge.org/BashGuide
http://www.gnu.org/software/bash/manual/bashref.html

The tldp stuff is great, however there are some bad habits in it,
The mywiki.wooledge does a very good job of 'fixing' those habits


All times are GMT -5. The time now is 12:55 PM.