You can use this modified script:
#!/bin/bash
# Script to add a user to Linux system
if [ "$(id -u)" -eq 0 ]; then
read -p "Enter username : " username
read -p "Enter password : " password
IFS=' ' read -a grps -p "Enter group names : "
if grep "^${username}:" /etc/passwd &>/dev/null; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
if useradd -m -p "$pass" "$username" &>/dev/null; then
echo "User has been added to system!"
for grp in "${grps[@]}"; do
usermod -a -G "$grp" "$username" && echo "User is added to group $grp" \
|| echo "Failed to add user to group $grp"
done
else
echo "Failed to add a user!"
fi
fi
else
echo "Only root may add a user to the system"
exit 2
fi
Note that you should always quote the variables.
Here i have added mainly two things:
IFS=' ' read -a grps -p "Enter group names : "
will ask root to give space separated group names to which the newly created user will be a member of
Then this short for
loop over the values of the array grps
:
for grp in "${grps[@]}"; do
usermod -a -G "$grp" "$username" && echo "User is added to group $grp" \
|| echo "Failed to add user to group $grp"
done
Given the groups already exist. If not you can use groupadd
to create the group and then add the user to that group.
Here we have used usermod
to add the user to an existing group, these groups will be supplementary groups for the user.
Check man usermod
for details.
Note that you should not use egrep
, it is deprecated in favor of grep -E
. In fact in this case you don't need grep -E
.
Your grep
pattern will fail in certain cases e.g. if you have a user foobar
and you are adding a new user named foo
. To overcome this, match the username followed by a :
(given no username has :
) :
grep "^${username}:" /etc/passwd &>/dev/null
Also send STDERR to /dev/null
too.
This can be simplified as:
if grep "^${username}:" /etc/passwd &>/dev/null; then
echo "$username exists!"
exit 1
else ......
Also the next if
statement with useradd
can follow this.
**Also some other improvements can be made to your current script, that would not fit in this context.