2015-07-21 43 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