Creating a user with a 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:
[root@codetryout ~]# useradd testuser && echo testuser-password | passwd testuser --stdin
Changing password for user testuser.
passwd: all authentication tokens updated successfully.
Creating a user with a password with predefined values
- Predefine usernames and passwords in variables.
- Do a useradd with the pre-defined variables
Example:
[root@codetryout ~]# user=newuser
[root@codetryout ~]# pass=newpassword
[root@codetryout ~]# 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 two lines of /etc/passwd to verify it.
[root@codetryout ~]# 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?
[root@codetryout ~]# userdel -r testuser
[root@codetryout ~]# userdel -r newuser
Dockerfile – how to create a user with password on the fly?
Another practical usage for this is creating a user with a pre-defined password in the docker file.
#
# 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.