簡體   English   中英

如何測試命令管道的輸出

[英]How to test output of command pipeline

這兩行

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

給我: binary operator expected

但是當我刪除管道符號時| 它有效,如何使用正在執行的管道制作命令? 我正在使用sh

您收到該錯誤是因為$($isEnabled)擴展$($isEnabled)並且[ -z ]需要一個參數。

  • 需要將myFunc(true)放在單引號或雙引號中,因為()具有特殊含義
  • 最好將$indexFile用雙引號括起來以防止出現同樣的問題

您可以為sh重寫代碼:

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

或者,更直接地說:

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
}

或者,在 Bash 中使用[[ ]]

function some {
  local isEnabled=$(grep 'myFunc(true)' "$indexFile" | grep true)
  if [[ $isEnabled ]]; then
    : your logic here
  fi
}
  • [[ $var ]][[ -z $var ]][[ -n $var ]] 只要$var的長度 > 0,它就會評估為真。

  • 無需將[[ ]]內的變量用引號括起來 - Bash 處理擴展沒有任何分詞或通配符擴展問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM