简体   繁体   English

如何测试命令管道的输出

[英]How to test output of command pipeline

These two lines这两行

 function some {
         ## myFunc(true) is just a pattern
         local isEnabled="grep myFunc(true) $indexFile | grep true"
         if [ -z $($isEnabled) ]; then ... fi
     }

give me : binary operator expected给我: binary operator expected

but when I remove pipe symbol |但是当我删除管道符号时| it works, how to make command with pipe being executed ?它有效,如何使用正在执行的管道制作命令? I am using sh我正在使用sh

You are getting that error because $($isEnabled) is expanding to nothing and [ -z ] requires an argument.您收到该错误是因为$($isEnabled)扩展$($isEnabled)并且[ -z ]需要一个参数。

  • need to put myFunc(true) in single or double quotes since () has special meaning需要将myFunc(true)放在单引号或双引号中,因为()具有特殊含义
  • it is better to enclose $indexFile in double quotes to prevent the same issue最好将$indexFile用双引号括起来以防止出现同样的问题

You can rewrite your code for sh :您可以为sh重写代码:

function some {
  local isEnabled=$(grep 'myFunc(true)' "$indexFile" | grep true)
  if [ -z "$isEnabled" ]; then
    : your logic here
  fi
}

Or, more directly as:或者,更直接地说:

function some {
  # just interested in the presence or absence of a pattern
  # irrespective of the matching line(s)
  if grep 'myFunc(true)' "$indexFile" | grep -q true; then
    : your logic here
  fi
}

Or, use [[ ]] in Bash:或者,在 Bash 中使用[[ ]]

function some {
  local isEnabled=$(grep 'myFunc(true)' "$indexFile" | grep true)
  if [[ $isEnabled ]]; then
    : your logic here
  fi
}
  • [[ $var ]] is as good as [[ -z $var ]] or [[ -n $var ]] . [[ $var ]][[ -z $var ]][[ -n $var ]] It will evaluate to true as long as $var has a length > 0.只要$var的长度 > 0,它就会评估为真。

  • no need to enclose variables inside [[ ]] in quotes - Bash handles the expansion without any word splitting or wildcard expansion issues.无需将[[ ]]内的变量用引号括起来 - Bash 处理扩展没有任何分词或通配符扩展问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM