【问题标题】:String Bash scripting if then statement fails如果 then 语句失败,则字符串 Bash 脚本
【发布时间】:2014-03-26 21:06:23
【问题描述】:

我目前正在编写一个脚本,允许我通过用户输入添加组。我在脚本的一部分中,用户在其中键入组名,并将其与 /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."

【问题讨论】:

  • 除了不使用getent吗?
  • 我想验证当前不存在的组是/etc/group。
  • 现在,您在读取组名之前尝试使用 grep 获取组名。 当然那会失败。
  • 感谢大家的帮助:)

标签: linux string bash if-statement scripting


【解决方案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:以前从未听说过getent。在谷歌上查了一下,发现this。有趣...
【解决方案2】:

这就是你要做的:

  1. 搜索组名
  2. 输入要搜索的组名

遗憾的是,您不能在输入之前搜索组名,因为这会违反因果关系和我们所知道的时空定律。在您知道要搜索的内容后尝试搜索:

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

【讨论】:

  • grep -q "^$group:" </etc/group 会更有效(不需要cat 进程,它除了从文件中读取并写入管道之外什么都不做,而是让grep 直接从文件中读取)。
猜你喜欢
  • 2019-02-09
  • 2021-08-27
  • 2010-10-14
  • 2015-02-24
  • 2014-09-12
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
  • 1970-01-01
相关资源
最近更新 更多