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

Grepping /etc/group works, but only on a machine where /etc/nsswitch.conf has:

group: files

meaning that only /etc/group is consulted when determining available groups. Use:

getent group <groupname>

for a more generic solution, checking the exit status: 0 means "exists", non-zero means "does not exist". For example, to check to see if group 'postgres' exists, and create it if it does not (assuming bash shell, running as a user able to create new groups) run:

/usr/bin/getent group postgres 2>&1 > /dev/null || /usr/sbin/groupadd postgres