This should work for you or at least help you get in the right direction:
#! /usr/bin/env bash -
#set -x
MY_INPUT='/root/temp/input'
declare -a A_SURNAME
declare -a A_NAME
declare -a A_USERNAME
declare -a A_DEPARTMENT
declare -a A_PASSWORD
while IFS=, read -r COL1 COL2 COL3 COL4 COL5 TRASH; do
A_SURNAME+=("$COL1")
A_NAME+=("$COL2")
A_USERNAME+=("$COL3")
A_DEPARTMENT+=("$COL4")
A_PASSWORD+=("$COL5")
done <"$MY_INPUT"
for index in "${!A_USERNAME[@]}"; do
useradd -g "${A_DEPARTMENT[$index]}" -d "/home/${A_USERNAME[$index]}" -s /bin/bash -p "$(echo "${A_PASSWORD[$index]}" | openssl passwd -1 -stdin)" "${A_USERNAME[$index]}"
done
The while
loop will read through your csv
file and create arrays for each column. the TRASH
value is there to collect any additional fields that may be in your csv
file. Otherwise if you had this for example: surname,name,username,department,password,anextrafield
COL5
would be set to: passwordanextrafield
Regardless, I think setting the arrays may not be necessary for you (as you could likely just create your users inside the while loop) but I wanted to show this way I've learned to work with looping through a delimited file.
After the for
loop will run through the index values of the A_USERNAME
array (It could have been any of the arrays) and act on them to create users.
useradd
-g "${A_DEPARTMENT[$index]}"
- This will add the newly created user to a group named after their department (note: this group must exist already or the command will error)
-d "/home/${A_USERNAME[$index]}"
- This will set the home directory for the newly created user to
/home/[USERNAME]
-s /bin/bash
- Set the login shell of the newly created user to
/bin/bash
-p "$(echo "${A_PASSWORD[$index]}" | openssl passwd -1 -stdin)"
- Takes the password from your csv and uses openssl to generate an MD5 password with it
"${A_USERNAME[$index]}"