Write a bash script to create users and groups systematically

In this article, we are going to learn how to create users and groups through a shell script.

Write Script:

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:

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]}" 
done

How this script works

In this script, we have used while and for loops. The while loop will read our .csv file. It will create arrays for each column. We used -d for the home directory, -s for the bash shell, and -p for the password.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Related Articles