3

How can I check if a group does not have users and delete it?

I'm doing a bash linux script, and I need to delete a group with the groupdel command, but I have to validate that the group I'm going to remove is empty, which does not have users.

This is what I have done:

  bajagroup () {
printf "\ nEnter the name of the group to delete: \ n"
read -r remove group
[ -n $ deletegroup ] && groupdel $ deletegroup
if [ $? -ne 0 ]; then
                 echo "The group was not deleted from the system. Please try again."
         else
                 echo "The group was deleted from the system."
fi
sleep 3
}

Something similar to the delgroup command with the --only-if-empty option, but with the groupdel command.

Example: delgroup --only-if-empty

  • It's not sufficient to look at users, but at files which happen to use that group (and happen to be accessible). Deleting the group gives you just a number for the group-id. – Thomas Dickey Jul 16 '17 at 18:53
1

Getting the members of a group in Linux isn't as easy as one might think. In my opinion the easiest way would be using the lid command. Install it using

sudo apt-get update && sudo apt-get install libuser

then you should try if it works using

lid -g root

If it says command not found try

/usr/sbin/libuser-lid -g root

And for your script

bajagroup () {
printf "\n Enter the name of the group to delete: \n"
read -p groupname #the variable has to be one word(normally)
deletegroup=$(lid -g $groupname)
[ -z $deletegroup ] && groupdel $deletegroup #between $ and the name no space

Edit

Since you can't install the package I wrote a little script that should solve your problem

#!/bin/bash
read -p "Enter groupname here: " groupname #Takes the input and save it to the variable groupname
gid=$(cat /etc/group | grep ^"$groupname": | cut -d":" -f3) #get the content of /etc/group (list of every group with groupid) | search for the line that starts with $groupname: (That means if a group name is Test, Test1 or 1Test wouldn't be matched) | get the groupid
member=$(cat /etc/passwd | cut -d":" -f4 | grep -x "$gid") #get the content of /etc/passwd (list of all users with some extra information like the attached gid) | get the part with the gid | grep the line that is exactly $gid
[ -z $member ] && groupdel $groupname #if $member is empty then delete that group

This is the base you need. You can change the ending and beginning to your needs.

  • Great, thank you so much, the problem is that I have to run this script on a computer with OpenSuse and it is an old version. Therefore, I can not install that package on the computer. – chelomvd Jul 16 '17 at 17:03
  • @user240991 I wrote a script that should substitute the package. – ADDB Jul 16 '17 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.