Thursday, October 28, 2021

[SOLVED] How to check if a group exists and add if it doesn't in Linux Shell Script

Issue

this is a summary of what i want my code to do:

if (group exists)
then

  (add user to group)

else

  (create group)

  (add user to group)

fi

I am using the Ubuntu virtual machine but all of the results i have found on similar sites do not work.


Solution

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


Answered By - Rupesh