How to create a new user and set a password in a single command (Linux/CentOS/Docker/Container)

Creating a user with password in one line

You can use the below command line combination:

useradd USERNAME && echo PASSWORD | passwd USERNAME --stdin

Note the –stdin at the end, which will request passwd command to accept the password from standard input.

Example:

[[email protected] ~]# useradd testuser && echo testuser-password | passwd testuser --stdin
Changing password for user testuser.
passwd: all authentication tokens updated successfully.

Creating a user with password, with predefined values

  • Predefine username and passwords in variables.
  • Do a useradd with the pre-defined variables

Example:

[[email protected] ~]# user=newuser
[[email protected] ~]# pass=newpassword
[[email protected] ~]# useradd $user && echo $pass | passwd $user --stdin
Changing password for user newuser.
passwd: all authentication tokens updated successfully.

Verifying whether the user accounts have been created

Let us look into the last 2 lines of /etc/passwd to verify it.

[[email protected] ~]# tail -2 /etc/passwd
testuser:x:1003:1004::/home/testuser:/bin/bash
newuser:x:1004:1005::/home/newuser:/bin/bash

Cleanup – How to delete test user accounts?

[[email protected] ~]# userdel -r testuser
[[email protected] ~]# userdel -r newuser

Dockerfile create user with password

Another practical usage for this is in the docker file, creating a user with a pre-defined password.

#
#   2 ENV variables or variables used in this Dockerfile
#   ${NEWUSER}  - This is the username
#   ${NEWUSER_PASSWORD} - This is the password for ${NEWUSER}
#
useradd ${NEWUSER} && echo ${NEWUSER_PASSWORD} | passwd ${NEWUSER} --stdin

This experiment explains the steps for quickly creating a Linux user with a password in one line. This works in standard Unix/Linux/Debian/Cloud/Docker image/container Linux environments.