Bash – Delete every users from a group

bashgroupusers

I search a clean way to delete every users from the 'sudo' group. On several distributions the user created during the installation process has sudo rights, I don't want this. I search for an automated method working for (nearly) every situations.

Basically, I want to empty a group.

To remove every users : GROUP=my_group; for u in $(getent group $GROUP | sed -e 's/^.*:.*:.*://' -e 's/,/ /g'); do echo gpasswd --delete $u $GROUP; done
This command line works :
1. if the group doesn't exist
2. if the group is empty
3. if the group contains one user
4. if the group contains several users
So everything is okay. But is their something simplier ?

Another way is to delete the group, and recreate it. Ugly ?

Best Answer

In general you shouldn't delete a group because some files may belong to that group but it may be sufficient for your specific sudo usecase.

A more general usecase is to use gpasswd (1) at it allows you to set the members of a specific group, so it should be enough to run:

gpasswd sudo -M ''

To only run this if the group sudo exists you can combine it with a getent call, i.e.:

getent group sudo && gpasswd sudo -M ''
Related Question