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.
- Check for Root User:
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.
- Prompt for Username:
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.
- Prompt for User Alias:
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.
- Prompt for Expiry Date:
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.
- Prompt for Password Inactive Days:
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.
- Prompt for Primary Group:
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.
- Prompt for Secondary Group:
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.
- Prompt for Home Directory:
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.
- Prompt for Default Shell:
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.
- Create the User:
cmd="useradd $alias $expirydate $pwexpiry -g $pgroup $sgroup -d $hdir $dshell $username"
eval $cmd
- This constructs and executes the
useradd
command with all the provided options.
- Set Ownership and Permissions:
bash chown $username:$pgroup $hdir
chmod 755 $hdir
- This sets the ownership and permissions for the home directory.