简体   繁体   中英

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

but when I remove pipe symbol | it works, how to make command with pipe being executed ? I am using sh

You are getting that error because $($isEnabled) is expanding to nothing and [ -z ] requires an argument.

  • need to put myFunc(true) in single or double quotes since () has special meaning
  • it is better to enclose $indexFile in double quotes to prevent the same issue

You can rewrite your code for 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:

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 ]] . It will evaluate to true as long as $var has a length > 0.

  • no need to enclose variables inside [[ ]] in quotes - Bash handles the expansion without any word splitting or wildcard expansion issues.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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