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

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.

No comments have been made. Use this form to start the conversation :)

Leave a Reply