X

Check if Linux group exists using bash shell

In this example, I will use the getent command to check if a Linux group exists.

if getent group "$groupname" >/dev/null; then
  echo "Group $groupname exists"
fi

Replace $groupname with the name of the group you want to check.

If you like to check if the group does not exist (e.g. because you like to create it in this case, then you can negate the command using the "!" operator.

if ! getent group "$groupname" >/dev/null; then
  echo "Group $groupname does not exit, adding it now"
  groupadd $groupname
fi

In this command, the ! operator is used to negate the exit code of the getent command.

Remember to replace $groupname with the actual name of the group or to define a variable of that name in your bash script.

Till Brehm:
X

Headline

You can control the ways in which we improve and personalize your experience. Please choose whether you wish to allow the following:

Privacy Settings