我正在撰寫一個樣式檢查腳本:
- 使用 grep 尋找一些風格的濫用
- 列印一條訊息和有問題的行,如果它們被發現
- 否則,不列印任何內容
我目前正在使用
if (grep -Erq 'break;|continue' *) then
echo && echo "found breaks and/or continues:"
grep -Ern 'break;|continue' *
else echo "no breaks or continues found."
fi
有沒有辦法存盤第一個 grep(帶有 -q 標志的 if 條件中的那個)的結果以供稍后使用(在 echo 陳述句之間),或者如果我想列印出來,我是否必須進行兩次搜索中間回聲訊息?我知道這個特定問題有一些簡單的解決方法;這是我想要大規模做的事情的一個較小的例子。
uj5u.com熱心網友回復:
你可以使用:
grep -ERn 'break;|continue' * && {
echo "^-- Found breaks or continues."
exit # or return, if you put this code in a function.
}
echo "No breaks or continues found."
uj5u.com熱心網友回復:
您可以將 grep 結果存盤在一個變數中,然后使用它(感謝 @CharlesDuffy 糾正我的評論):
if offending=$(grep -Ern 'break;|continue' *)
then
printf '\n%s\n%s\n' 'found breaks and/or continues:' "$offending"
else
echo 'No breaks or continues found.'
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/372415.html
