Write a bash script to create users and groups systematically

February 24, 2021

Comments

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.

Satish Kumar

Satish Kumar

I am Satish Kumar, Founder of LinuxConcept. Linux and F.O.S.S enthusiast, love to work on open source platform and technologies.

Related Posts

Calculating and reducing the runtime of a script

In this article, we are going to learn how to calculate and reduce the script’s runtime. A simple time command will help in calculating the execution time.PrerequisitesBesides having a terminal open, make sure you have the necessary scripts present in your...

Using Bash to monitor battery life and optimize it

In this article, we will learn about the TLP Linux tool. TLP is a command-line tool; it is used for power management and will optimize the battery life.PrerequisitesBesides having a Terminal open, you need to ensure that you have TLP installed on your system.How to do...

0 Comments

0 Comments

Submit a Comment

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

16 − thirteen =

News & Updates

Join Our Newsletter