How to Add New Users in Linux in Bash Script

Naila Saad Siddiqui Feb 02, 2024
How to Add New Users in Linux in Bash Script

This short article is about creating a Bash script that can automatically add users and assign passwords to the Linux operating system. In the Linux operating system, the useradd command is used to add new users and give them passwords.

Bash Script useradd Command

A simple utility for adding users is useradd. Administrators on Debian should typically use adduser instead.

Invocation of the useradd command without the -D option creates a new user account by the values entered on the command line and the system default values. The useradd command updates system files and may perform other tasks depending on command-line options.

Additionally, make the home directory for the new user and copy the initial files.

Bash Script to Add User

In Linux operating system, we need to be root users to add new users to the system. Therefore, in the script, we first need to validate whether or not the user running the script is a root user.

After that, we can take the input username and password from the user and then run the useradd command. Let us look at the script below.

Bash Script:

#!/bin/bash

if [ $(id -u) -eq 0 ]; then
    read -p "Enter your  username : " user_name
    read -s -p "Enter your password : " pass
    egrep "^$user_name" /etc/passwd >/dev/null
    if [ $? -eq 0 ]; then
        echo "$user_name exists!"
        exit 1
    else
        epass=$(perl -e 'print crypt($ARGV[0], "pass")' $pass)
        useradd -m -p "$epass" "$user_name"
        [ $? -eq 0 ] && echo "Successfully added User!" || echo "Sorry! User not added"
    fi
else
    echo "Sorry! You are not authorized to add users."
    exit 2
fi

After reading the username and password from the user, we first searched if the user with the given username already exists or not using the egrep command. If the user entry is found in the /etc/passwd file, it means the user already exists.

Otherwise not, we will encrypt the password using the perl command. The perl command will show the screen with the encrypted password.

The crypt() function in Perl employs a one-way encryption algorithm, making it impossible to decrypt a password once it has been encrypted. The user’s password string is obtained, encrypted using salt, and then displayed on the computer screen.

After running the useradd command, we will check the result using the $? value and show the appropriate message to the user.

Output:

output of the bash script of useradd command

Related Article - Bash Command