【问题标题】:Behaviour of grep's return codegrep 返回码的行为
【发布时间】:2016-09-05 11:32:03
【问题描述】:

我在这里和其他地方看到了许多问题的答案,这些答案说您可以通过回显变量并将其传递给 grep 来对变量进行 grep 搜索。但是,遵循这些示例的语法对我不起作用。

以下代码失败,每次都回显“找到”,无论我使用grep 搜索什么字符串。我做错了什么?

TEST='This is a test of the emergency broadcast system.'
echo $TEST | grep 'blah'
if [ $? -eq 0 ]
then
    echo 'not found'
else
    echo 'found'
fi

【问题讨论】:

  • 退出状态0一般表示成功...

标签: regex bash macos grep


【解决方案1】:

你的支票应该反过来。

来自man grep

EXIT STATUS
       The  exit  status is 0 if selected lines are found, and 1 if not found.
       If an error occurred the exit status is 2.  (Note: POSIX error handling
       code should check for '2' or greater.)

看一个例子:

$ echo "hello" | grep h
hello
$ echo $?
0
$ echo "hello" | grep t
$ echo $?
1

但是,最好使用Bash tools

[[ $TEST =~ *blah* ]] && echo "found" || echo "not found"

【讨论】:

  • 就是这样。有趣的是,我从来没有想过 0 意味着找到了东西。
  • @T.Reed 是的,这很有误导性(至少对我而言)。我曾经认为 0 -> N0 -> NO -> False。
【解决方案2】:

零在 shell 脚本中表示 true。你甚至可以像这样简化它:

TEST='This is a test of the emergency broadcast system.'
if echo "$TEST" | grep 'blah'
then
    echo 'found'
else
    echo 'not found'
fi

【讨论】:

  • 确实不是的意思;这意味着成功
  • 我不认为这两种说法是相互排斥的。
  • if 将退出状态解释为布尔值,0 评估为 true,其他任何值评估为 false
  • 因此“零对if 语句表示正确”。
  • 不,零并不意味着任何地方都是真的。零是命令的成功退出状态,if command 测试command 的退出状态。如果你写了if ( cmd() == 0 ) {do success stuff},这就像在 C 中一样。该声明也不意味着零也意味着正确。说零表示正确是 100% 错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-22
  • 2017-07-04
  • 1970-01-01
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多