Linux: How to Create a User and Add to Group in a Single Line?

This is a common question for Linux Admins. It would be necessary to memorize the syntax of this command (assuming non Active Directory or LDAP integrated machines):

sudo adduser <username> -g <groupname>

This similar keyword command would also work

sudo useradd <username> <groupname>

This command would also work if the user has already been created

sudo usermod -aG <groupname> <username>

Beyond answering the basic question, it’s important to understand the application and implication of those commands. Let’s discuss that below.

In the real world, Linux Admins receive onboarding requests often. Besides creating a user, it’s also important to set the home directory, shell environment, group memberships, etc.  Therefore, it would be necessary to have a bash shell handy to automate accounts generation such as this one:


# Declare an array of string called username.
# Note that bash shell interprets comma or space as delimiters
usernames=("kimconnect" "somethingconnect")

# group
group = "permitssh"

# use openssl to generate md5 hash string as password
password=$(openssl passwd -1 "DEFAULT_INIT_PASSWORD")

# iterate through the array
for user in "${usernames[@]}"
# Create user with password, group, home directory, and login bash environment.
useradd $user -p $password -g $group -d /home/$user -s /bin/bash

When dealing with multiple servers, use this method to add users to multiple machines.

a. Create a List of users:

General format:


Example (null values for UID & GID to assume defaults):

kimconnect:passy1:::"Kim Connect","001","555-555-5555","555-555-5555","Accounting":"/home/kimconnect":"/bin/bash"
dragoncoin:passy2:::"Jimmy Bond","007","555-555-5555",,"Information Technology":"home/dragoncoin":"/bin/bash"

b. Create a list of Servers

cat << ENDCAT > /home/kimconnect/servers.txt

b. Create shell script, set it as executable, and run it

# Create Shell File
cat << ENDCAT > /home/kimconnect/
ssh-keygen -t rsa
while read server;
do ssh-copy-id -i ~/.ssh/ root@$server;
done < servers.txt

# Set script as executable
chmod a+x /home/kimconnect/

# Execute the script on the predetermined list of servers < servers.txt

The usage of scripting to generate domain or LDAP accounts is outside the scope of this document. That should be covered it this blog somewhere.

Posted on Categories Linux

Leave a Reply

Your email address will not be published. Required fields are marked *