グループにユーザーがいないことを確認して削除する方法は?

グループにユーザーがいないことを確認して削除する方法は?

グループにユーザーがいないことを確認して削除する方法は?

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

これがあなたに必要な基礎です。必要に応じて終了と開始を変更できます。

おすすめ記事