How to create a user from a file in Bash?

2019-09-20 10:23发布

问题:

I have a file called user.txt with around one hundred entries that are in this format: user:password:group:shellToUse

ex. :

martin:pwd123:photo:bash
marc:pwd321:devel:c-shell
...

How can I create users by reading the entries in this file with a Bash script?

Also, the home directory of the users must look like /home/group/user, and the default shellToUse is Bash.

回答1:

If your user have the necessary privileges you could use something like the following

filename="$1"
while IFS=: read uName pw group shell; do
    shell=${shell:-bash}
    # if shell is the empty string, set $shell to bash
    shell_path=$(which $shell)
    useradd -d /home/$group/$uName $uName -g $group -s $shell_path
    echo -e "$pw\n$pw\n | passwd $uName
done < "$filename"
unset IFS

call the script in the following way: ./script_name user.txt

and do not forget to make the script executable, i.e.

chmod u+x script_name

as mklement0 suggest, this should speed up the script.

i do not understand the comment about shell=${shell:-bash}

useradd manpage

passwd manpage



回答2:

If you use bash, the pseudo code looks something like this

Open file and read lines 
for eachline in lines:
    Split the line using awk. Take hints from  https://viewsby.wordpress.com/2012/09/14/awk-split-string-using-a-delimiter/ 
    use 'adduser' command to create user with password. Take hints from http://www.tecmint.com/add-users-in-linux/ 


标签: linux bash shell