将整数作为参数并打印这些数字的总和,但出现找不到命令的错误
takes integers as arguments and prints the sum of those numbers but getting command not found error
我想从命令行获取参数并打印整数的总和。但是如果没有给出参数那么它应该给我总计 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
。
试试这个:
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
我想从命令行获取参数并打印整数的总和。但是如果没有给出参数那么它应该给我总计 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
。
试试这个:
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