接受整数作为参数并打印这些数字的总和,但出现命令未找到错误
我想从命令行获取参数并打印整数之和。但如果没有给出参数,那么它应该给我总计为 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,这是正确的,但在没有给出参数时它不起作用。
我收到错误总计:未找到命令
。
I want to take arguments from command line and print the sum of the integer. But if there is no argument given then it should give me total as 0.
Example vi sum.sh contains below code
total=0
for i in $@; do
(( total+=i ))
done
echo "The total is $total"
bash sum.sh
Then this should give me output as 0
Similarly if I give bash sum.sh 1 2
then output coming as 3 which is correct but its not working when there is no arguments given.
I am getting error total: command not found
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
试试这个:
当您使用变量的值时,需要在它前面加上美元符号。
最重要的是,您需要
$((...))
来执行计算。编辑:示例
我已将这段脚本放入一个名为
test.sh
的文件中,并进行了以下测试(及其结果):Try this:
When you use the value of a variable, it needs to be preceded by a dollarsign.
In top of that, you need
$((...))
to perform calculations.Edit: example
I have put this piece of script in a file, called
test.sh
and did the following test (with its result):