我想從命令列獲取引數并列印整數的總和。但是如果沒有給出引數,那么它應該給我總計為 0。
示例 vi sum.sh 包含以下代碼
total=0
for i in $@; do
(( total =i ))
done
echo "The total is $total"
bash sum.sh
那么這應該給我輸出為0
同樣,如果我給出bash sum.sh 1 2
輸出為 3,這是正確的,但在沒有給出引數時它不起作用。
我收到錯誤total: command not found。
uj5u.com熱心網友回復:
嘗試這個:
total=0
for i in $@; do
total=$(($total $i ))
done
echo "The total is $total"
當你使用一個變數的值時,它前面需要一個美元符號。
最重要的是,您需要$((...))執行計算。
編輯:示例
我將這段腳本放在一個檔案中,呼叫test.sh并進行了以下測驗(及其結果):
Prompt> sh test.sh 1 2 6
The total is 9
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/449843.html
