我目前正在编写一个脚本,允许我通过用户输入添加组。我在我的脚本部分,用户键入组名称,并将其与/ etc / group进行比较,让用户知道是否需要添加。我已经针对一个我已经知道的事实测试了这个事实不在我的系统上并且它只读取我的循环中的第一个语句。有人能告诉我哪里出错了吗?
#!/bin/bash
echo "This script will allow you to enter Groups and Users needed for new builds"
echo
echo
echo
echo
# Setting Variables for Group Section
Group=`cat /etc/group |grep "$group"`
echo -n "Please enter the group name that you would like to search for..press [ENTER] when done: " # Request User input to obtain group name
read group
echo "Searching /etc/group to see if the group "$group" exists." # Checking to see if the group exists
if [ "$group" != "$Group" ]; then
echo "The group already exist. Nothing more to do buddy."
else
echo "We gotta add this one fella..carry on."
答案 0 :(得分:1)
如果您使用的是Linux,那么getent
可用:
printf "Group to search for: "
read -r group
if getent group "$group" >/dev/null 2>&1; then
echo "$group exists"
else
echo "$group does not exist"
fi
使用getent
使用标准C库进行目录查找。因此,它不仅适用于/etc/passwd
,/etc/group
等,还适用于Active Directory,LDAP,NIS,YP等目录服务。
答案 1 :(得分:0)
这是你做的:
可悲的是,在输入之前你无法搜索群组名称,因为这会违反我们所知道的因果关系和时空规律。在您知道搜索内容后尝试搜索:
echo -n "Please enter the group name that you would like to search for..press [ENTER] when done: " # Request User input to obtain group name
read group
if cat /etc/group | grep -q "^$group:"
then
echo "The group already exist. Nothing more to do buddy."
fi