2015-07-21 22 views
0

我需要通過命令巴什腳本檢查,如果多組存在

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 
+0

如果這是一塊工作代碼,你只是在尋找改進/建議將其放置在http://codereview.stackexchange.com/ – depperm

回答

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

我輸入你會組用逗號分隔很多組。如果輸入是單個用戶,這將工作。 –

+0

我已經更新了我的答案。 – Cyrus

+0

如果我要求解釋//./ 哈哈對不起,我對這件事感興趣 –

0
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