簡體   English   中英

在bash中的命令管道序列中執行條件命令

[英]Conditional command execution within piped sequence of commands in bash

抱歉崎嶇的主題名稱(如果您在查看問題后找到更合適的標題,請隨時編輯)。 代碼示例等於1000個單詞,所以我們在這里:

if [ "$REGEX" != "" ]; then
        find $TEST_DIR -type f -regextype posix-extended -regex '^.*(status|stderr|stdout)-captured$' |                                  
        grep -E $REGEX |
        awk '{print(""$1" "$1)}' | sed 's/-captured$/-expected/' | 
        while read -r line; do mv -f $line; done 
else
        find $TEST_DIR -type f -regextype posix-extended -regex '^.*(status|stderr|stdout)-captured$' |
        awk '{print(""$1" "$1)}' | sed 's/-captured$/-expected/' |
        while read -r line; do mv -f $line; done
fi

什么代碼並不是那么重要,我只是想找到更優雅的方式來使用“ grep -E $ REGEX ”或不使用。 我認為conditdonal別名可以完成這項工作,就像我習慣使用shell一樣,但它們在腳本中不起作用。

我可以提出一個條件,但我擔心多次評估會對性能產生影響。

有什么辦法讓代碼“更優雅”?

一個非常簡單的解決方案:

test -n "$REGEX" && cmd="grep -E $REGEX"
find ... | ${cmd-cat} | awk ...

如果定義了cmd,則在管道中使用它。 否則,使用cat,執行no-op。 你也可以這樣做:

find ... |
if test -n "$REGEX"; then
  grep -E $REGEX
else
  cat
fi |
awk ...

具有完全相同的效果。

一種簡單的方法是使用^ (總是匹配:它表示“行開頭”,每行都有)如果$REGEX未設置或為空:

find $TEST_DIR -type f -regextype posix-extended -regex '^.*(status|stderr|stdout)-captured$' |
grep -E ${REGEX:-^} |
awk '{print(""$1" "$1)}' | sed 's/-captured$/-expected/' |
while read -r line; do mv -f $line; done

就此而言,您可以將其組合到原始find

find $TEST_DIR -type f -regextype posix-extended \
     -regex '^.*(status|stderr|stdout)-captured$' \
     -regex ".*${REGEX}.*" |
awk '{print(""$1" "$1)}' | sed 's/-captured$/-expected/' |
while read -r line; do mv -f $line; done

就此而言,您可以將所有其余腳本合並到find中:

find $TEST_DIR -type f -regextype posix-extended \
     -regex '^.*(status|stderr|stdout)-captured$' \
     -regex ".*${REGEX}.*" \
     -exec bash -c 'file="{}" ; mv -f "$file" "${file%-captured}-expected"' \;

這是一個稍微丑陋但一般的解決方案。

find $TEST_DIR -type f -regextype posix-extended -regex '^.*(status|stderr|stdout)-captured$' \
 | if [ "$REGEX" != "" ]; then
        grep -E $REGEX; \
   else \
        cat; \
   fi \
 | awk '{print(""$1" "$1)}' \
 | sed 's/-captured$/-expected/' \
 | while read -r line; do mv -f $line; done 

暫無
暫無

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

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