我正在撰寫一個腳本來檢查(使用 If 陳述句)變數是否包含特定字符。如果找到一個字符,腳本將執行一些代碼。如果找不到某個字符,腳本將進入另一個 If 陳述句來檢查變數是否包含另一個特定字符,依此類推。
這一切都很好。
但是我需要腳本來告訴我是否找不到任何字符,但我在實作這個目標時遇到了一些麻煩。腳本看起來像這樣。
if [[ "$results" == *"specific character"* ]]; then
do something.
fi
if [[ "$results" == *"specific character"* ]]; then
do something.
fi
if [[ "$results" == *"specific character"* ]]; then
do something.
fi
如果所有這些 If 陳述句都找不到它們的字符,我需要腳本來回顯找不到這些字符。
我試圖在所有其他 If 陳述句周圍放置一個 If/else 陳述句,但這對我不起作用。
if [[ ]]; then
if [[ "$results" == *"specific character"* ]]; then
do something.
fi
if [[ "$results" == *"specific character"* ]]; then
do something.
fi
if [[ "$results" == *"specific character"* ]]; then
do something.
fi
else
echo "characters are not found."
我似乎無法讓它作業。有人能給我一個正確的方向嗎?
親切的問候,
光滑
uj5u.com熱心網友回復:
使用case陳述句:
case "$results" in
*c*) do something;;
*d*) do something;;
*e*|*f*) do something
do another thing;;
*) echo "characters are not found.";;
esac
uj5u.com熱心網友回復:
您可以在 if 主體中設定一個變數,然后檢查它是否已設定,如下所示:
...
if [[ "$results" == *"specific character"* ]]; then
foundsmth=1
fi
if [[ -z ${foundsmth} ]] ; then
# nothing found
fi
另一種解決方案是將正則運算式與 switch-case 結構結合使用,如此處所述。
uj5u.com熱心網友回復:
對于您if周圍的個人if陳述,您可以使用正則運算式:
if [[ $str =~ [abc] ]]; then
if [[ "$str" == *"a"* ]]; then
echo "a"
fi
if [[ "$str" == *"b"* ]]; then
echo "b"
fi
if [[ "$str" == *"c"* ]]; then
echo "c"
fi
else
echo "None of those characters are in str"
fi
uj5u.com熱心網友回復:
我通常更喜歡case像丹尼斯這樣的人。因為你已經把它寫成 了if,你可以使用一個復合的 if/elif/else,只要在檢查它們之前短路是可以的。
if [[ "$results" == *"specific character"* ]]
then : do something.
elif [[ "$results" == *"specific character"* ]]
then : do something.
elif [[ "$results" == *"specific character"* ]]
then : do something.
else echo "characters are not found."
fi
另一方面,如果您需要全部檢查它們,無論是否在此程序中找到任何東西,您將需要 mju 的標志變數。
found=0;
if [[ "$results" == *"specific character"* ]]
then ((found )); : do something.
fi
if [[ "$results" == *"specific character"* ]]
then ((found )); : do something.
fi
if [[ "$results" == *"specific character"* ]]
then ((found )); : do something.
fi
((found)) || echo "characters are not found."
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/536845.html
標籤:狂欢if语句
