[英]Bash scripting check condition
我是 bash 腳本的新手,並嘗試編寫以下簡單的
function wait_some {
if [ -z $1 ];
echo some_string
then if ! [[ $1 =~ ^[0-9]+([.][0-9]+)?$ ]];
then
echo "$1 is not a number"
exit 2
else echo "it's a number"
fi
fi
}
wait_some 2.2 //prints some_string and then it's a number
這按預期工作。
但是如果我刪除 echo "some string' 它什么都不打印:
function wait_some {
if [ -z $1 ];
then if ! [[ $1 =~ ^[0-9]+([.][0-9]+)?$ ]];
then
echo "$1 is not a number"
exit 2
else echo "it's a number"
fi
fi
}
wait_some 2.2 //prints nothing
為什么? 為什么在條件檢查破壞函數后立即刪除echo some_string
?
這是因為if-condition
在bash
作為復合語句執行,即command1
; command2
以及測試運算符中-z
錯誤用法。
我將通過我對這兩個示例的set -x
選項進行的調試來解釋它。
對於成功者,這就是執行順序
++ wait_some 2.2
++ '[' -z 2.2 ']'
++ echo some_string
some_string
如您所見,執行的兩個條件[ -z 2.2 ]
失敗。 但為什么? 因為字符串的長度非零( 查看-z
是 如何工作的)並且檢查導致條件失敗,這應該是[ ! -z 2.2 ]
[ ! -z 2.2 ]
。 並不止於此。
由於您使用的組合命令集, command1
; command2
command1
失敗的if-condition
,現在command2
只是一個簡單的echo
成功運行,並帶有正返回碼,使整體if-condition
成功,導致正則表達式搜索,您可以看到后續的echo'ed
語句。
現在對於失敗的情況, set -x
的擴展結果看起來像
++ wait_some 2.2
++ '[' -z 2.2 ']'
如您所見,刪除echo
語句后, if-condition
的整體返回代碼變為 false,並且根本不執行內部條件。 同樣刪除echo
語句類似於在腳本中實際添加一個false
運算符,例如
if [ -z $1 ];
false
這將擴展到
++ wait_some 2.2
++ '[' -z 2.2 ']'
++ false
導致你的條件失敗。 你的腳本應該被編碼的理想方式是這樣的
#/bin/bash
# See the updated if-condition and code reorganization
function wait_some {
if [ ! -z "$1" ];
then
if ! [[ $1 =~ ^[0-9]+([.][0-9]+)?$ ]];
then
echo "$1 is not a number"
exit 2
else echo "it's a number"
fi
fi
}
wait_some 2.2
關於您的錯誤的最好的事情是甚至http://www.shellcheck.net/無法識別if-condition
的錯誤語法並斷言腳本沒有任何問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.