Home » BASH » Write a bash script to create users and groups systematically

Write a bash script to create users and groups systematically

Last updated May 17, 2021

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.

Related Posts

Creating a config file and using it in tandem with your scripts

In this article, we are going to create a config file and use it in our shell script.PrerequisitesBesides having a terminal open, you need basic knowledge of creating scripts and config files.Write scriptNow, we are going to create a script and config file. The...

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...

Creating a simple NAT and DMZ firewall using bash script

In this article, we will create a simple NAT firewall with DMZ using iptables.PrerequisitesBesides having a Terminal open, you need to ensure that iptables is installed in your machine.Write scriptWe will write a script to set up a DMZ using iptables. Create...

Follow Us

Our Communities

More on BASH

The Ultimate Managed Hosting Platform
Load WordPress Sites in as fast as 37ms!

0 Comments

0 Comments

Submit a Comment

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

5 + nineteen =

Shares