Posted: . At: 9:30 AM. This was 9 years ago. Post ID: 8378
Page permalink. WordPress uses cookies, or tiny pieces of information stored on your computer, to verify who you are. There are cookies for logged in users and for commenters.
These cookies expire two weeks after they are set.

A simple shell script to create a new Linux user account.

This simple script will help create new user accounts on a Linux system. This is very useful when administering a Linux machine and it is necessary to create a few user accounts.

#!/bin/bash
 
clear
 
trap "" SIGHUP SIGINT SIGTERM SIGTSTP
 
# Get username, check if its taken, and if it is the proper length.
while true
do
        echo -n "Create username: "
        read username
        if [ ${#username} -gt 0 ]
        then
                if [ $(cat /etc/passwd | grep $username) ]
                then
                        echo "Username already exists. Please choose another one."
                elif [ ${#username} -gt 2 ] && [ ${#username} -lt 10 ]
                then
                        break
                else
                        echo "Username must be between 2 to 10 characters."
                fi
        else
                echo "Username can not be blank."
        fi
 
done
 
# Get the password and check if they match.
while true
do
        echo -n "Password: "
        read password
        echo -n "Confirm password: "
        read password_confirm
        if [ ${#password} -gt 0 ] || [ ${#password_confirm} -gt 0 ]
        then
                if [ $password == $password_confirm ]
                then
                        break
                else
                        echo "Passwords do not match."
                fi
        else
                echo "Password can not be blank."
        fi
done
 
# Add user
useradd $username -m -s /bin/bash -G users
 
# Give user password
echo $username:$password | chpasswd
 
echo "Account created! Please login to your new account."
 
kill -HUP $PPID

Here I am running this script on Ubuntu to test it out.

Create username: jasonx
Password: 302c64
Confirm password: 302c64
Account created! Please login to your new account.

And the new user account works just fine.

ubuntu ~ $ su jasonx
Password:
jasonx@ip-172-31-20-16:/home/ubuntu$

If you no longer need the user account, just lock it.

ubuntu ~ $ sudo passwd -l jasonx
passwd: password expiry information changed.

More information about useradd here: http://linux.die.net/man/8/useradd. Information about the chpasswd command here: http://linux.die.net/man/8/chpasswd.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.