以下是我希望我的代码所做的工作的总结:
if (group exists)
then
(add user to group)
else
(create group)
(add user to group)
fi我正在使用Ubuntu虚拟机,但我在类似站点上发现的所有结果都不起作用。
发布于 2015-03-16 09:36:55
此脚本可能会帮助您:
read -p "enter group name: " group
if grep -q $group /etc/group
then
echo "group exists"
else
echo "group does not exist"
fi发布于 2016-03-21 12:36:38
grep语句在rups解决方案中存在一些缺陷:
例如,组grepping admin在存在组lpadmin时可以返回true (“组存在”)。
要么修复grep-query
grep -q -E "^admin:" /etc/group或使用
if [ $(getent group admin) ]; then
echo "group exists."
else
echo "group does not exist."
fi发布于 2017-09-04 15:46:53
Grepping /etc/group工作,但仅在/etc/nsswitch.conf具有:
group: files这意味着在确定可用组时只会咨询/etc/group。使用其中任何一种(按名称或按gid):
getent group <groupname>
getent group <groupid>对于更一般的解决方案,检查退出状态:0表示“存在”,非零表示“不存在”。例如,要检查组'postgres‘是否存在,如果不存在,则创建它(假设bash shell,以能够创建新组的用户身份运行)运行:
/usr/bin/getent group postgres 2>&1 > /dev/null || /usr/sbin/groupadd postgreshttps://stackoverflow.com/questions/29073210
复制相似问题