2

如何将 bash shell 脚本中的变量与小于 1 进行比较?

我以前做过,但我得到'1:没有这样的文件或目录'

grep_result=`grep -r $ID . | wc -l`

echo $grep_result
# it said '1: No such file or directory'
if [ $grep_result < 1 ]; then
    echo "Wrong id.
    exit 1
fi
4

4 回答 4

3

从 bash 的角度来看,这意味着将调用的文件通过管道传输1到 $grep_result 变量中。-lt在这种情况下,您需要使用运算符。(le 代表小于)

grep_result=`grep -r $ID . | wc -l`

echo $grep_result
# it said '1: No such file or directory'
if [ $grep_result -lt 1 ]; then
    echo "Wrong id.
    exit 1
fi
于 2012-11-21T19:10:28.987 回答
1

检查不匹配的正确方法是

if ! grep -q -r "$ID" . ; then
    echo Wrong id.
    exit 1
fi

没错:if 的目的if是运行命令并检查其退出代码。 grep如果匹配,则返回成功退出代码,否则返回 1(错误)。大多数 Unix 工具都是这样编写的,正是为了这个目的。

在有匹配项时获取计数是一个小的修改:

if matches=$(grep -r "$ID" .) ; then
    echo "$matches" | wc -l
else
    echo Wrong Id.
    exit 1
fi

请注意使用grep -q只返回错误代码而不打印任何内容。如果您只是想从单个文件中计数(或每个文件的匹配数)grep -c打印它。

于 2012-11-21T19:42:17.203 回答
1

以下是更改代码的 2 种不同方法:

路线#1:

将您的代码更改为:

grep_result=$(grep -r $ID .)

echo $grep_result

if [ -z "$grep_result" ]; then
    echo "Wrong id."
    exit 1
fi

解释:

  • grep_result=$(grep -r $ID .):grep -r $ID .在子 shell 中运行并将结果输出保存stdoutgrep_result. 该$(...)符号称为命令替换,并且优于使用反引号以提高可读性+允许嵌套命令
  • if [ -z "$grep_result" ]; then: "test" shell 内置-z选项检查是否为空字符串;如果是,则条件评估为真。["$grep_result"

路线#2:

或者,或者:

grep_result_count=$(grep -rc $ID .)

echo $grep_result_count

if [ $grep_result_count -eq 0 ]; then
    echo "Wrong id."
    exit 1
fi

解释:

  • grep_result_count=$(grep -rc $ID .):与上面类似的想法,但请注意我们使用的是-rc选项grep而不是-r; 选项的c一部分表示“不输出匹配的行,只输出找到多少匹配的数字”。所以在这种情况下,你会得到一个大于或等于 0 的整数。
  • if [ $grep_result_count -eq 0 ]; then:-eq这里的选项检查它左边的值是否等于它右边的值。在这种情况下,我们检查上一个 grep 命令的匹配数是否正好等于 0。
于 2012-11-21T19:12:15.863 回答
0

您还可以使用更有效的方法:

if ! grep -qr "$ID" . ; then
    echo "Wrong id."
    exit 1
fi

希望这可以帮助。

使用该-q选项,grep只需保持安静,一旦找到模式就停止(如果可以找到),如果找到模式则输出true返回值,false否则。这可能是解决您的问题的最有效方法。

于 2012-11-21T19:28:25.083 回答