如何在Linux中删除组– groupdel命令

时间:2020-02-23 14:39:30  来源:igfitidea点击:

Linux groupdel命令用于删除组。
这是一个非常强大的命令,因此请谨慎使用。
这是常见的Linux命令,您可以在所有Linux发行版中使用它,例如Ubuntu,CentOS,Debian,Fedora等。

我们来看一些使用groupdel命令在Linux中删除组的示例。

Linux删除没有用户的组

对于该示例,我已经创建了几个组和一个测试用户。
让我们看一个简单的示例,删除一个没有用户的组。

root@localhost:~# getent group test_users1
test_users1:x:1005:
root@localhost:~#
root@localhost:~# groupdel test_users1
root@localhost:~# getent group test_users1
root@localhost:~# 

与用户删除组

我创建了一个" test_users"组,并向其添加了" theitroad"用户。
让我们使用" getent"和" id"命令进行确认。

root@localhost:~# getent group test_users
test_users:x:1004:theitroad
root@localhost:~# 

root@localhost:~# id theitroad
uid=1002(theitroad) gid=1003(theitroad) groups=1003(theitroad),27(sudo),1004(test_users),1007(test_users_pwd)
root@localhost:~#

让我们看看删除该组时会发生什么。

root@localhost:~# groupdel test_users
root@localhost:~# id theitroad
uid=1002(theitroad) gid=1003(theitroad) groups=1003(theitroad),27(sudo),1007(test_users_pwd)
root@localhost:~# getent group test_users
root@localhost:~# 

该组将被删除,并从用户组列表中删除。

我们可以使用groupdel命令删除系统组吗?

我们可以使用groupdel命令删除系统级别组吗?

让我们尝试使用groupdel命令删除sudo组,看看会发生什么。

root@localhost:~# groupdel sudo
root@localhost:~#  id theitroad
uid=1002(theitroad) gid=1003(theitroad) groups=1003(theitroad),1007(test_users_pwd)
root@localhost:~# getent group sudo
root@localhost:~# 

看来我们能够删除" sudo"用户组。
让我们来看看该用户的超级用户特权发生了什么。

root@localhost:~# su - theitroad
theitroad@localhost:~$
theitroad@localhost:~$ls /root
ls: cannot open directory '/root': Permission denied
theitroad@localhost:~$sudo ls /root
[sudo] password for theitroad: 
theitroad is not in the sudoers file.  This incident will be reported.
theitroad@localhost:~$

看起来sudo特权也被删除了,这很明显,因为我们删除了" sudo"组本身。

删除用户的主要组

当我们创建一个新用户时,还将创建一个具有相同名称的新组并将其分配给它。
这称为用户的主要组。

让我们看看是否可以删除用户的主要用户组?

root@localhost:~# groupdel theitroad
groupdel: cannot remove the primary group of user 'theitroad'
root@localhost:~#

让我们看一下帮助选项,看看是否有任何方法可以克服此错误消息?

root@localhost:~# groupdel -h
Usage: groupdel [options] GROUP

Options:
-h, --help                    display this help message and exit
-R, --root CHROOT_DIR         directory to chroot into
-f, --force                   delete group even if it is the primary group of a user

root@localhost:~# 

输出清楚地表明,我们可以使用-f选项删除用户的主要组。

root@localhost:~# groupdel -f theitroad
root@localhost:~# id theitroad
uid=1002(theitroad) gid=1003 groups=1003
root@localhost:~# 

我们能够删除用户的主要组。
但是," gid = 1003"仍显示在用户信息中。
因此,我不知道此功能的用例是什么。

Linux groupdel命令退出值

如果您在Shell脚本中使用groupdel命令,最好知道退出值,以检查命令是否执行正常或者出现错误。

Exit ValueDescription
0success
2invalid command syntax
6the group doesn't exist
8can't delete user primary group
10can't update group information files