簡體   English   中英

Bash腳本檢查是否存在多個組

[英]Bash scripting check if multiple groups exists

我需要使用以下命令將用戶添加到多個補充組中

usermod -aG group1,group2 username

需要幫助以進行錯誤檢查,以便腳本可以搜索/ etc / group文件中是否存在多個組。 這就是我所擁有的。

read -p "Enter groups" groups
if (Check if those groups exists)
then
  usermod -aG "$groups $username
else
  echo "Group(s) does not exists"
fi

請幫忙謝謝! 對不起,我是一個新手,如果可能的話,請告訴我一些閱讀鏈接。

好吧,我提出了一些切實可行的方法。 如果它可以被某人“清理”,將不勝感激。 XD

    read -p "Enter user" user
    read -p "Enter groups" groups
    storegroups=$(echo $groups | awk -F, '{print $1" "$2" "$3}')
    if [ "$(getent group $storegroups | wc -l)" == $(echo $storegroups | wc -w)" ]
    then 
        usermod -ag $groups $user
    else
        echo "1 or more groups does not exists"
    fi
#!/bin/bash

read -p "Enter username: " username
read -p "Enter groups: " groups

for g in ${groups//,/ }; do
  grep -q "^$g:" /etc/group
  ret=$?                         # save returncode of grep
  if [[ $ret -eq 0 ]]; then
    usermod -aG "$g" "$username"
  else
    echo "Group $g does not exists"
  fi
done
read -p "Enter user: " user
read -p "Enter groups: " groups

# Replace , with space
groupswithSpace=$(echo $groups | tr ',' ' ')

#getent returns 0 only if all groups are valid
getent group $groupswithSpace > /dev/null

if [ $? -eq 0 ]
then
    usermod -ag $groups $user
else
    echo "1 or more groups does not exists"
fi

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM