我是Bash的新手,在创建脚本时遇到了问题。该脚本的作用是取数字并将其加到总计中。但是,我无法获得合计的工作。它不断声称合计是一个不变的变量,尽管它已在程序的早期分配。
错误信息(输入的数字是8)
./adder: line 16: 0 = 0 + 8: attempted assignment to non-variable (error token is "= 0 + 8")
#!/bin/bash
clear
total=0
count=0
while [[ $choice != 0 ]]; do
echo Please enter a number or 0 to quit
read choice
if [[ $choice != 0 ]];
then
$(($total = $total + $choice))
$(($count = $count + 1))
echo Total is $total
echo
echo Total is derived from $count numbers
fi
done
exit 0
除去变量名前面的一些美元符号。在算术上下文中,它们是可选的,即((...))
。在分配的左侧,它们不仅是可选的,而且还是被禁止的,因为=
需要左侧的变量名而不是其值。
也$((...))
应为纯((...))
,且没有前导美元符号。美元符号将捕获表达式的结果,并尝试将其作为命令运行。它将尝试运行名为0
或5
或任何计算值的命令。
您可以写:
((total = $total + $choice))
((count = $count + 1))
或:
((total = total + choice))
((count = count + 1))
甚至:
((total += choice))
((count += 1))