≡ Menu

Linux Shell script to add a user with a password to the system

Our regular reader Imtiaz asks:

How do I add a user with password? I’d like to take input such as username, password from keyboard and add to the system under Linux.

A. You can easily write a shell script that reads username, password from keyboard and add to /etc/passwd and /etc/shadow file using useradd command (create a new user command).

General syntax is as follows:
useradd -m -p encryptedPassword username


  • -m : The user’s home directory will be created if it does not exist.
  • useradd -p encryptedPassword : The encrypted password, as returned by crypt().
  • username : Add this user to system

Task: Create an encrypted password

You need to create encrypted password using perl crypt():
$ perl -e 'print crypt("password", "salt"),"\n"'


Above will display the crypted password (sa3tHJ3/KuYvI) on screen. The Perl crypt() function is a one way encryption method meaning, once a password has been encrypted, it cannot be decrypted. The password string is taken from the user and encrypted with the salt and displayed back on screen.

You can store an encrypted password using following syntax:
$ password="1YelloDog@"
$ pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
$ echo $pass



Sample shell script to add a user

Based upon above discussion here is a sample shell script (Download link):

# Script to add a user to Linux system
if [ $(id -u) -eq 0 ]; then
	read -p "Enter username : " username
	read -s -p "Enter password : " password
	egrep "^$username" /etc/passwd >/dev/null
	if [ $? -eq 0 ]; then
		echo "$username exists!"
		exit 1
		pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
		useradd -m -p $pass $username
		[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
	echo "Only root may add a user to the system"
	exit 2

Close and save the script:
$ ./adduser.sh
Only root may add a user to the system

Run as root:
# ./adduser

Enter username : roja
Enter password : HIDDEN
User has been added to system!

Now user roja can login with a password called HIDDEN.

Share this on:
{ 65 comments… add one }
  • Amol P Kesare March 22, 2007, 5:22 am

    I just want to send one script which I have made for changing password of any user from remote machine.
    Here I have created one file called “host” which contents host ips.

    Shell script code

    read -p "Enter Username: " username
    read -ers -p "Enter New password for user $username: " paswd
    read -ers -p "Enter Root Password: " rpaswd
    password=`python file ${paswd}`;
    echo "$username $password $npaswd"
    cat host | while read line
    status=$(expect -c "
    spawn ssh $line usermod -p $password $username
    expect {
    password: { send \"$rpaswd\n\"; exp_continue }
    echo ""
    echo "$status" > log.txt
    #####end of expect#######

    python code – file [for crypt()]

    import crypt; import sys; print crypt.crypt(sys.argv[1],”salt”);

    Hope this will help somebody. :)

  • nixCraft March 22, 2007, 8:27 am


    Nice script.

    Appreciate your post.

  • Amol P Kesare March 22, 2007, 9:52 am

    Hey forgot one thing….there is one more file called “file”, and contents of these files are –

    import crypt; import sys; print crypt.crypt(sys.argv[1],”salt”);

  • nixCraft March 22, 2007, 9:59 am

    Yes, i thought so… there is line about python… thanks

  • Allotment March 23, 2007, 1:00 pm

    I always wondered if there was a bash /CLI command to list the users, is there?
    I see here
    egrep “^$username” /etc/passwd >/dev/null

    so there is not?

    • naushad February 10, 2011, 9:15 am

      egrep -v ^xyz /etc/passwd | cut -d”:” -f1

      Add this line in a script which displays all the users in your machine
      i have used ^xyz , Starting with that. genarally user names will never start with that , so we get the desired result as output becouse of the option -v .

      • naushad February 10, 2011, 9:29 am

        As a root
        vim usershow
        1 #!/bin/bash
        2 #this script displays the users in machine.
        3 egrep -v ^xyz /etc/passwd | cut -d”:” -f1 |less
        cp usershow /usr/local/sbin/
        chmod -R +x /usr/local/sbin
        Thats it…Enjoymaadi

  • nixCraft March 23, 2007, 2:25 pm

    Remove ‘>/dev/null‘ and you should see username if exists in /etc/passwd. To display list just type:

    cut -d: -f1 /etc/passwd

  • master March 26, 2007, 7:22 am

    its great but it is more powerful if you include the functionality to add lage number of users at once
    like in my uni more then 15000 stuent it is almoste inpossible to create their acccounts one by one

  • nixCraft March 26, 2007, 6:54 pm


    You may take help of this my previous post – How to create multiple users accounts in batch / bulk


  • balakrishnan.R April 13, 2007, 11:24 am

    How I need edit the script to add the user in particular group and disable them by accessing telnet.


    useradd -d /home/example1 -s /bin/false -g popusers example1

  • Amol P Kesare April 17, 2007, 6:03 am

    ># Allotment Says:
    >March 23rd, 2007 (4 weeks ago) at 1:00 pm
    >I always wondered if there was a bash /CLI command >to list the users, is there?
    >I see here
    >egrep “^$username” /etc/passwd >/dev/null
    >so there is not?

    You can use gawk to list users
    gawk -F: ‘{ if ( $3>500 ) print $1 }’/etc/passwd

  • Fabio May 9, 2007, 5:03 pm

    Could you kindly help me to integrate in this first script to add a user in /etc/shadow from a comma separeted file?
    I would like to export a list from a company application, create a .csv , and lunch it from a shell script or a php page in a website to import users in 1 step.
    The important is that the password used to access sistem by users is the one I can read in clear characters in the csv file.
    Let me know please, and put my address in copy fabio@conecta.it

  • bhushan August 10, 2007, 6:56 am

    egrep “^$username” /etc/passwd

    don’t u people think that this will not match string
    perfectly means if there is user like bhushan and i want to create user bhush…then it will give msg that user already exists…

  • nixCraft August 10, 2007, 7:18 am

    Sure you can use word based matching:

    egrep -w “^$username” /etc/passwd
  • Slavko August 10, 2007, 8:02 am

    (echo "username:password")|chpasswd

  • bhushan August 14, 2007, 10:43 am

    hi vivek,
    how to add user without using useradd command?
    With all information such as uid(by incrementing existing highest one), gid,…….etc.

  • Tyler McAdams August 18, 2007, 4:20 pm

    I need a shell script that will create a password for users already on the system. How can I do that?

  • Artem Nosulchik September 19, 2007, 2:45 pm

    Another way to get encrypted password is command:

    openssl passwd yourpass

  • Eric Daza June 6, 2008, 4:09 am

    PASSWORD checking is limited to 8 characters long.

    I tried the Script above (adduser.sh), and the password checking is some how up-to 8 characters only. Meaning as long as you have the first 8 characters correct you can login to the system (I tested using su command)
    The part I changed on the script is to set username and password as a variable:



    it will allow secr3t12333333333 or secr3t12

    • SuseHead March 3, 2014, 8:31 pm

      I found the same thing. 8 characters and it ignores the rest.

      How do you make it store more than 8 characters?

  • Lakh December 18, 2008, 7:14 pm

    How can you also get this script to add a samba password at the same time it creates a unix password?

  • Lonnie Waugh February 2, 2009, 5:55 pm

    Useful article, I was was looking to add users with a one liner so this helped .. since Debian lacks the crypt command, I didn’t even think to use perl ..

    Since I maintain the web server we use, exclusively .. I know all of my accounts have home directories, so I simply do my test to see if a user exists in perl .. but the same could be done in a shell script

    if (-e “/home/$username”) {
    print “The account already exists bonehead!”;
    } else {
    // get on with it

  • laknath February 21, 2009, 7:41 pm

    i compile this program but when i move to the second part I cant execute it in root . I got a error???

    No such file or directory

    why is that ???
    pls reply me….

  • rapsa March 16, 2009, 2:32 pm

    how about this one liner script

    # useradd -m -p `perl -e ‘print crypt(“your_password”, “salt”),”\n”‘` your_username

  • palani March 25, 2009, 7:23 am

    how to create new user to assign perssion to particular shell and set userid and groupid make this one line command

  • Mukundan May 28, 2009, 3:01 pm


    I like to add bulk of user using bash scripting taking the user name from a text file from a given location and also want to set a sample passwd for the all user who have been created. and also the script has to mail to the corresponding user regarding the username and passwd . Can anyone help me out

    Thanks in advance

  • Gordon June 2, 2009, 10:29 pm

    Sample shell script to add a user

    How do I change this to add the users full name ans login shell

  • Charanjit Singh July 5, 2009, 8:59 am

    Hi Vivek(nixcraft)
    Your mentioned shell script giving me an error message while executing it
    “line 19: syntex error: unexpected end of the file”
    Please check and where it is get stuck..
    Charanjit Singh

  • Dnyan August 17, 2009, 4:50 pm

    Hi all,

    Can someone let me know, How to write script for password expiry notification in solaries.

  • Ravi Sajjan October 23, 2009, 8:25 am

    Hello Everyone,
    My self Ravi and I am trying to make one PHP page, from which i can able to create
    new user in linux. where in php code will show three boxes
    1.) New User Name:
    2.) Password:
    3.) Botton: Add now
    with this php code i want to add new user in linux through web interface.

    Kindly please help me out to do that so.


  • Harold Osborn January 15, 2010, 4:30 am

    i need to help me. i want to good 100% user email, password and forget password.
    frisrt sign user email then get get password number in then open in base.
    if forget password then send email get password
    Can anyone help me thank harold

  • majo053 February 6, 2010, 11:23 pm

    simple: echo PASSWORD | passwd USER –stdin

  • Servando August 18, 2010, 6:25 pm

    It was very useful your sample,



  • soumyav August 26, 2010, 3:58 pm

    Hey I need a scrip to add 100 users to UNIX server using an Input file which has two input one full name the other username . But i need to generate password in the script which gets incremented with each added user ….

    Thanks a lot in advance ….


  • Anil December 23, 2010, 1:14 pm

    Very good script.

  • hemanth January 7, 2011, 11:26 am

    hi guys
    can any one tell me how to write a script such that the script reads the password and enters to tat user

  • John April 23, 2011, 5:13 am

    i just want to know the script
    Write a shell script that can be used to:
    Detailed requirements
    1. The script can only be executed by the root user, administrator or users with administrative rights.
    2. If the root user starts the program as specified, it should read the input file and check the new users’ information one by one. If a new user’s information is valid, it should create the account for the user and write the account information to a report file. The report file should have the following format:
    3. If a new user’s information is not valid, it should not create the account for the user. The error should be written to an error report file. You need to specify the file format.
    4. If the root user executes the script incorrectly, e.g., without the necessary parameters or with incorrect parameters, it should provide an appropriate help message to the user. For example, it could show the correct usage of the command.
    5. If the root user executes the command with the –h switch, the program should give detailed information about the program and the file structure of the input file.
    6. The input file should have the following structure:
    • Each line is a user record.
    • Each record has four fields separated by commas (,) as follows:
    Note: The password field must be between 9 and 12 characters long. The field for the user’s full name may contain blank spaces. You must specify the features of the other fields. If a group does not exist, the program should create a default group automatically.

  • jyothi August 18, 2011, 5:07 am

    pass=$(perl -e ‘print crypt($ARGV[0], “password”)’ $password)
    in this block what does $ARGV[0] stores and how it will work

  • franka October 3, 2011, 6:42 am

    we really appreciate your useful code

  • please help me November 3, 2011, 8:29 pm

    The student should write a bash program named myuseradd that accepts a list of users as argument

    Script syntax: myuseradd [ [ ..]]

    At least one argument must be provided and must not exceed 10 alphanumeric characters.

    The script must not use the usedadd or similar commands. It must:

    1- Check if user is root. If not the script cannot be run and it exits.
    2- Check the number of arguments. If none the script exits.
    3- Check if is already used, if yes the script exits.
    4- Ask the user to provide the following data:
    a. Home directory:
    Default is /home/
    The script accepts either /home/ or /. must
    not exceed 10 alphanumeric characters and the entered home directory
    must not exist already.
    b. Login shell
    Default is /bin/bash
    The script can accept one of the shells as listed in /etc/shells.

    If provided data does not meet conditions, the user is asked to enter the data again

    5- Add user with name , provided home directory and login shell to the system’s users (/etc/passwd file).

    6- Assign userid (must be the first available userid greater or equal to 500).

    7- Create a new group with group name and gid same as uid and assign it as primary group. This must be done by adding an entry to /etc/group.If the group already exists, no change is done.

    8- Create home directory and set required permissions.
    9- Copy startup scripts to the home directory (from /etc/skel).

    10- Create a line in /etc/shadow that corresponds to the user with a blank password.

    11- Call the passwd program to set the password.

    12- Produce an output the summarize what it did.

  • yang March 16, 2012, 9:24 pm

    Very appreciated!
    I am working a project started from another team in another continent. The document/help we get is zero. So we are on our own.
    During the boot, I am stopped by login/password. There are several ways to crack in.
    By using your script, I easily add a user(ie, myself) into the system. It works painlessly. Thank you so much!

  • ferr0 April 23, 2012, 3:13 pm

    to change the password ->
    echo “User_name:PASSWORD” | chpasswd

  • Toni Weber May 22, 2012, 8:11 pm

    I found an very easy way to do this:

    For System-Password:
    # echo -e “\n”|passwd

    For SAMBA-Password:
    # echo -e “\n”|smbpasswd -sa

    In some configuration the System-Password will changed with smbpasswd also!
    Check /etc/samba/smb.conf for Password-Chat

  • sameet August 2, 2012, 7:59 am

    hello i m new in unix can anyone tell me how to write a bash script which prompts user and assigns a password?

  • Menard October 1, 2012, 8:08 pm

    The sample scripts are great.

  • Sanjib N. February 1, 2013, 9:24 am

    This script really help me in creating mass user accounts for students.


  • Willis November 8, 2013, 12:46 am

    Quality contribution appreciate it

  • Amols June 10, 2014, 9:07 am

    I am using this script but when i run these script it ask me username and when i entered Password i am getting error Failed and when i am not entering password it succesfully create user. Please let me know what i missing..


  • Craig June 19, 2014, 4:43 pm

    I’m learning UNIX. I would like a script to add a user account (id and password) to multiple UNIX servers. I currently use smit user when a new employee begins working which takes forever because we have over 100 UNIX servers. Please help.

  • Annie February 6, 2015, 10:37 am

    is there a way to do this so you dont have to be the root? im having problems with permissions as i am using a virtual machine so please reply as advice would be greatly appreciated.

  • mohit March 3, 2015, 1:09 pm

    hello Admin ,
    script having problen in creating user i.e mohit2 if a user mohit23 is present .
    it is not exactly grepping the user name from /etc.passwd.

    • Naushad Nazeer Pasha March 4, 2015, 3:47 am
      # Script to add a user to Linux system
      if [ $(id -u) -eq 0 ]; then
      	read -p "Enter username : " username
      	read -s -p "Enter password : " password
      	cut -d ":" -f 1 /etc/passwd | egrep "^$username$" >/dev/null
      	if [ $? -eq 0 ]; then
      		echo "$username exists!"
      		exit 1
      		pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
      		useradd -m -p $pass $username
      		[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
      	echo "Only root may add a user to the system"
      	exit 2
    • Naushad Nazeer Pasha March 4, 2015, 3:48 am

      I hope the newly given code will fix your issue, enjoy.

  • shailendra kalal March 6, 2015, 4:00 pm

    can any one please help on this ..

    i need to check around 1000 user’s for all details its mentioned in /etc/passwd.

    • Naushad Nazeer Pasha March 11, 2016, 10:52 am
      # Script to add user(s) to Linux system based on agrument as input to the script
      #usage "sh user.sh users-filename"
      for user in `cat $1`
      	if [ $(id -u) -eq 0 ]; then
      		egrep "^$user" /etc/passwd >/dev/null
      		if [ $? -eq 0 ]; then
      			echo "$user : User already exists!" >> /var/ucsd/user.sh.log
      			pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
      			useradd -m -p $pass $user
      			[ $? -eq 0 ] && echo "$user : User has been added to system!" >> /var/ucsd/user.sh.log || echo "Failed to add a user!" >> /var/ucsd/user.sh.log
      		echo "Failed to create user accounts, Only root may add a user to the system" >> /var/ucsd/user.sh.log
      		exit 2
  • pooja April 7, 2015, 4:56 am

    i need a program on shell script whether the username entered is correct to the password

  • DontHaveAName October 6, 2015, 3:09 pm

    Vivek Gite,
    Thanks very much for this posting, I have referenced this for my computing task!
    Would it be possible if you could explain this line by line so I understand how it works? The other thing was, is it possible to also add these users to groups by using the script too?
    Thanks once again!

  • Anonymous November 26, 2015, 11:02 am

    How would I add a user and then add them to a group if the user was inputted in a shell script?

  • no one January 26, 2016, 10:21 am

    what does the -p and -s -p do?

  • zuckerberg April 17, 2016, 7:01 pm
    #Shell script to create a new user
    echo " Enter Account Name:"
    echo " Enter Accounts' Password"
    read PASSVAR
    echo " Enter Group"
    read GROUPVAR
    net user $ACCOUNTVAR $PASSVAR /add
    net localgroup $GROUPVAR $ACCOUNTVAR /add
  • SAMULA HASSAN May 7, 2016, 6:08 am


  • mayur murkya July 7, 2016, 5:36 am


    We can use below command for user creation and its password entry.

    useradd mayur && echo -e “mayur@123\nmayur@123” | passwd mayur

    \n is for new line

  • Pradeep November 17, 2016, 4:51 am

    Hi Admin,
    i need a shellscript to add a new user to server
    +to access to ssh through i need to copy my public key in the currently created user path
    +i want to prevent root permission to new user
    +this steps need to be done in centos

  • Yolo November 23, 2016, 3:56 pm

    can you show how to do this?

    Write a script called simple-useradd.sh that adds a local user to the system. This script should:
    Take only one argument, or else exit after printing a usage message.
    . Check /etc/passwd and decide on the first free user ID. Print a message containing this ID.
    Create a private group for this user, checking the /etc/group file. Print a message containing the group ID.
    Gather information from the operator user: a comment describing this user, choice from a list of shells (test for acceptability, else exit printing a message), expiration date for this account, extra groups of which the new user should be a member.
    . With the obtained information, add a line to /etc/passwd, /etc/group and /etc/shadow; create the user’s home directory (with correct permissions!); add the user to the desired secondary groups.
    Set the password for this user to a default known string.

Security: Are you a robot or human?

Leave a Comment