Creating a User Account with Custom Settings in Linux
This article explains how to create a user account with various custom settings in Linux using a Bash script. The script prompts the user for input, checks for conditions, and executes the necessary commands. Below is the script with explanations for each command.
if [[ $(id -u) -ne 0 ]]; then
echo "run this script as root user"
exit 1
fi
This checks if the script is being run by the root user (id -u returns the user ID, and 0 is the root user ID). If not, it prints a message and exits.
while [[ -z $username ]]; do
read -p "username= " username
done
This loop continues to prompt the user for a username until a non-empty value is provided.
read -p "user alias= " alias
if [[ ! -z $alias ]]; then
alias="-c '$alias'"
fi
This prompts the user for an alias and adds it to the user creation command if provided.
read -p "expiry date= " expirydate
if [[ ! -z $expirydate ]]; then
expirydate="-e $expirydate"
fi
This prompts the user for an account expiry date and includes it in the command if provided.
领英推荐
read -p "password inactive days= " pwexpiry
if [[ ! -z $pwexpiry ]]; then
pwexpiry="-f $pwexpiry"
fi
This prompts the user for the number of days after the password expires before the account is disabled.
read -p "primary group= " pgroup
if [[ -z $pgroup ]]; then
pgroup=$username
fi
if [[ $(grep -c $pgroup /etc/group) -eq 0 ]]; then
groupadd $pgroup
fi
This checks if the primary group exists, creates it if not, and sets it for the user. If no primary group is provided, it defaults to the username.
read -p "secondary group= " sgroup
if [[ ! -z $sgroup ]]; then
if [[ $(grep -c $sgroup /etc/group) -eq 0 ]]; then
groupadd $sgroup
fi
sgroup="-G $sgroup"
fi
This checks if the secondary group exists, creates it if not, and includes it in the user creation command if provided.
read -p "home dir= " hdir
if [[ -z $hdir ]]; then
hdir="/home/$username"
fi
mkdir $hdir
This prompts for the home directory, defaults to /home/username if not provided, and creates it.
read -p "default shell= " dshell
if [[ ! -z $dshell ]]; then
dshell="-s $dshell"
fi
This prompts for the default shell and includes it in the user creation command if provided.