Creating users and groups systematically
In this section, we are going to learn how to create users and groups through a shell script.
How to do it...
Now, we will create a script to add a user. The useradd command is used to create a user. We are going to use the while loop, which will read our .csv file, and we will use the for loop to add each user that's present in that .csv file.
Create a script using add_user.sh:
#!/bin/bash
#set -x
MY_INPUT='/home/mansijoshi/Desktop'
declare -a SURNAME
declare -a NAME
declare -a USERNAME
declare -a DEPARTMENT
declare -a PASSWORD
while IFS=, read -r COL1 COL2 COL3 COL4 COL5 TRASH;
do
SURNAME+=("$COL1")
NAME+=("$COL2")
USERNAME+=("$COL3")
DEPARTMENT+=("$COL4")
PASSWORD+=("$COL5")
done <"$MY_INPUT"
for index in "${!USERNAME[@]}"; do
useradd -g "${DEPARTMENT[$index]}" -d "/home/${USERNAME[$index]}" -s /bin/bash -p "$(echo "${PASSWORD[$index]}" | openssl passwd -1 -stdin)" "${USERNAME[$index]}"
doneHow it works...
In this recipe...