Max Max - 4 months ago 8
Bash Question

How to create a user from a file in Bash?

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.

Answer

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