Adding multiple users to Linux using BASH

Some or the other time as a sys admin you will come across a need to add multiple users to your Linux system. So the question is how to do the same.

Let us see how we can do the same in this post.

We will assume that N number of users are to be added with a standard prefix or suffix and values incrementing with numbers. e.g.  employee27... emp28.. etc

The command to add a user is useradd

The command can be simply run as:

useradd loginid/username

The above command simply creates  a new user account using the values specified on the command line plus the default values from the system. (see file /etc/default/useradd).

Keep in mind, the above command will create an entry in /etc/passwd, but might not create the home dir.

We need to create a user with home dir and to populate it with the structure from /etc/skel (The contents of this directory are replicated to new users home dir)

So we need to modify the command with some options of specifying the shell and home.

useradd -m -s /bin/bash -d /home/loginid -s /bin/bash loginid

in the above command

-m is used to populate the users home (replicate /etc/skel contents to users home)

-s is to specify the shell in this case we specify the full path to the shell i.e. /bin/bash (this could be any other as per your requirements)

-d is used to specify the home directory of the user, usually we keep it same as loginid of the user, but can be anything and can be at any other place required.

Now the above is to be automated using a script.  So assuming that  a series of users are to be created as specified above i.e. emp1...emp2...empN .. let us see how this is to be done.

We simply need a loop which runs from 1 to N, this is achieved in BASH using the for loop:

for i in 1 2 3 4 6 7 8 9 .... N
     run this code.

But above code can be improved by using a command 'seq'  it generates a seq of numbers, and that is what we need exactly!!

seq 1 10  

Gives 1 2 3 4 5 6 7 8 9 10. So we are going to use this in our loop

for i in `seq 1 10` 
     run this code.
Now to get the code to generate users.
for i in `seq 1 100`
     echo "useradd -m -s /bin/bash -d /home/${idprefix}${i} -s /bin/bash ${idprefix}${i}"

In the above code the value of ${idprefix}${i} keeps updating from emp1 to emp100, and the whole command is run for the N users creating multiple users in your system.

We will see more variation in next posts.

"Natraj"  Bungalow,
Colony No.7,  Sr.No. 38.
(Lane Behind Sai Baba Mandir)
Kale Borate Nagar, Hadapsar,
Pune - 411028.
Get Directions