How to check if a group exists and add if it doesn't in Linux Shell Script
The grep
statement in the solution of rups has some flaws:
E.g. grepping
for a group admin
may return true
("group exists") when there is a group lpadmin
.
Either fix the grep
-query
grep -q -E "^admin:" /etc/group
or use
if [ $(getent group admin) ]; then
echo "group exists."
else
echo "group does not exist."
fi
This script may help you:
read -p "enter group name: " group
if grep -q $group /etc/group
then
echo "group exists"
else
echo "group does not exist"
fi