如何检查群组是否没有用户并删除它?

如何检查群组是否没有用户并删除它?

如何检查群组是否没有用户并删除它?

我正在编写一个 bash linux 脚本,我需要使用 groupdel 命令删除一个组,但我必须验证要删除的组是否为空,并且没有用户。

这就是我所做的:

  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
}

类似于带有 --only-if-empty 选项的 delgroup 命令,但带有 groupdel 命令。

例子:delgroup --only-if-empty

答案1

在 Linux 中获取一个组的成员并不像人们想象的那么容易。在我看来,最简单的方法是使用命令lid。安装它使用

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

那么你应该尝试使用它是否有效

lid -g root

如果提示找不到命令,请尝试

/usr/sbin/libuser-lid -g root

对于你的脚本

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

编辑

由于您无法安装该软件包,我编写了一个小脚本来解决您的问题

#!/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

这就是你需要的基础。您可以根据需要更改结尾和开头。

相关内容