问题描述
这是我希望我的代码执行的摘要:
if (group exists)
then
(add user to group)
else
(create group)
(add user to group)
fi
我正在使用Ubuntu虚拟机,但在类似站点上发现的所有结果均无法正常运行。
最佳答案
该脚本可以帮助您:
read -p "enter group name: " group
if grep -q $group /etc/group
then
echo "group exists"
else
echo "group does not exist"
fi
次佳答案
rups解决方案中的grep
语句存在一些缺陷:
例如。当存在组lpadmin
时,组admin
的grepping
可能返回true
(“group exists”)。
修复grep
-query
grep -q -E "^admin:" /etc/group
或使用
if [ $(getent group admin) ]; then
echo "group exists."
else
echo "group does not exist."
fi
第三种答案
捕获/etc /group可以,但是只能在/etc/nsswitch.conf具有以下内容的机器上:
group: files
这意味着在确定可用组时仅参考/etc /group。使用:
getent group <groupname>
对于更通用的解决方案,请检查退出状态:0表示”exists”,非零表示“不存在”。例如,要检查组’postgres’是否存在,如果不存在,请创建该组(假设bash shell,以能够创建新组的用户身份运行),请运行:
/usr/bin/getent group postgres 2>&1 > /dev/null || /usr/sbin/groupadd postgres
第四种答案
我发现将Andiba的解决方案组合成适当的功能更加有用:
function grpexists {
if [ $(getent group $1) ]; then
echo "group $1 exists."
else
echo "group $1 does not exist."
fi
}
例如,可以通过在/etc/bash.bashrc*
中包含此函数来将其调用到您的环境中,以便您可以使用以下拼写检查组是否存在:
grpexists group_name
然后应该返回以下之一:
group group_name exists.
要么
group group_name does not exist.