我是 bash 腳本的新手,我使用函式撰寫了一個腳本來計算給定數字的階乘。該函式適用于零和正數,但它沒有給出負值的預期輸出。
這是我的腳本:
#!/bin/bash
# factorial program using a function with while loop
calculate_factorial () {
result=1
current=1
if(( $1 < 0 )); then
echo "The number cannot be negative"
elif(( $1 == 0 )); then
echo "1"
else
while(($current <= $1)); do
result=$(( result*current ))
current=$(( current 1 ))
done
#print the result
return $result
fi
}
calculate_factorial $1
echo $result
-8 的輸出:
The number cannot be negative
1
它應該只輸出The number cannot be negative,但我不知道1輸出的第二行來自哪里。
如果我有任何錯誤或解釋原因,如果您能發現我的錯誤,我將不勝感激。
uj5u.com熱心網友回復:
簡短的回答是因為您result=1在函式的開頭設定了(請注意,由于result未宣告為本地變數,因此它是全域變數),并且在主腳本的末尾設定了echo $result. result仍然設定為“1”,所以這就是它列印的內容。
更長的答案是您誤解了如何從函式回傳值。一般來說,函式可以產生三種結果:
要回傳資料(在本例中為階乘值),您應該將其列印到標準輸出(也稱為標準輸出,這是默認輸出目標)。您可以使用
echo或任何其他產生輸出的命令。不要為此使用命令return(見下文)。在這種情況下,您可以正確執行此操作(( $1 == 0 ))。如果在使用函式的時候需要捕獲輸出,可以使用
value=$(functname ...args...),但是這種情況下看起來就是無論如何都想列印,所以不需要捕獲輸出,直接去終端就好了.要回傳錯誤或狀態訊息(如“數字不能為負數”),請將其列印到標準錯誤(又名 stderr)而不是標準輸出。您可以使用 將命令的輸出重定向到標準錯誤
>&2。要回傳成功/失敗狀態,請使用
return命令(0=成功,非零=失敗)。這是您應該在命令中回傳的所有return內容(同樣,exit來自腳本的值)。如果您愿意,您可以使用不同的非零值來指示不同的問題,但大多數情況只使用 1 來表示所有錯誤。要檢查函式的回傳狀態,可以將其嵌入到
if陳述句中,或者在呼叫函式后$?立即檢查(它保存最新命令的狀態,因此如果您運行任何其他命令,它將替換它) .
此外,雙引號變數和引數參考(例如"$1",而不是 just )通常是良好的腳本衛生,$1以避免奇怪的決議。有一些例外,例如在(( ))運算式內部。此外,在內部(( ))或其他算術背景關系中,您不需要使用$來獲取變數的值。shellcheck.net它擅長指出這樣的事情。順便說一句,在 shell 語法中,空格是非常重要的分隔符。使用(之間沒有空格)恰好可以作業,但是養成將元素分開if((的習慣會更好(當然,除非它們不需要分開,例如)。if ((var=value
因此,這是您的函式的更正版本:
#!/bin/bash
# factorial program using a function with while loop
calculate_factorial () {
result=1
current=1
if (( $1 < 0 )); then
# Here, we print an error message to stderr
echo "The number cannot be negative" >&2
# and then return an error status
return 1
elif (( $1 == 0 )); then
# Here, we print the result to stdout
echo "1"
# and then return a success status
return 0
else
while (( current <= $1 )); do
result=$(( result*current ))
current=$(( current 1 ))
done
#print the result
echo "$result"
# and then return a success status
return 0
fi
}
calculate_factorial "$1"
uj5u.com熱心網友回復:
更改echo "The number cannot be negative"為result="The number cannot be negative
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/483481.html
上一篇:在Bash中更改資料集變數的值
