为什么bash中的$((sum&èx2B;=i))告诉我;未找到命令";?

为什么bash中的$((sum&èx2B;=i))告诉我;未找到命令";?,bash,scripting,Bash,Scripting,目标是创建一个bash脚本,将1到N的整数相加,其中N由用户定义。这是我的密码: #!/bin/bash read -p "Enter an integer greater than zero: " N #allows the user to enter a value, which is then read from stdin and assigned to N sum=0 for ((i=0; i<=N; i++)) do $((sum+=i)) #add i to

目标是创建一个bash脚本,将1到N的整数相加,其中N由用户定义。这是我的密码:

#!/bin/bash

read -p "Enter an integer greater than zero: " N  #allows the user to enter a value, which is then read from stdin and assigned to N

sum=0

for ((i=0; i<=N; i++))

do

  $((sum+=i))  #add i to sum each iteration

done

echo "The sum of the numbers from 1 to $N is $sum"

总和是正确的。我意识到每次迭代的求和都会导致某种错误(b/c0,1,3,6…是每个I的求和值),但我不确定为什么或如何修复它。有没有在vi中调试的方法?谢谢

$
放在前面:

((sum+=i))

$(())
将进行算术展开,展开的结果将被视为运行命令,导致错误消息。

使用冒号作为行的第一个字符可以避免此问题:

:  $((sum+=i))  #add i to sum each iteration
或删除
$

((sum+=i))  #add i to sum each iteration
$(())
的问题在于它有一个输出,而这个输出(没有:)
正在被解释为要执行的命令(1、3、6…等)

您可以将代码缩减为以下较短版本:

#!/bin/bash
read -p "Enter an integer greater than zero: " N  

for (( i=0,sum=0 ; i<N ; i++,sum+=i )); do : ; done

echo "The sum of the numbers from 1 to $N is $sum"

$(…)
$(…)
一样,将操作结果替换为要运行的新命令的内容。因此,如果
$((sum+=i))
的结果是3,它会尝试作为命令运行
3
。@CharlesDuffy so sum=$((sum+i))不会像$((sum+=i))那样实现命令替换。嗯。当我说“当前语法”时,我想我指的是heemayl的答案。抱歉--评论应该在那里,而不是在问题上。您的“简短”版本只略短,但不太清晰。未来扩展的唯一明显空间是将当前建议标记为bashism,并添加符合POSIX的替代方案。
#!/bin/bash
read -p "Enter an integer greater than zero: " N  

for (( i=0,sum=0 ; i<N ; i++,sum+=i )); do : ; done

echo "The sum of the numbers from 1 to $N is $sum"
#!/bin/bash
read -p "Enter an integer greater than zero: " N  
echo "The sum of the numbers from 1 to $N is $(( N*(N+1)/2 ))"