“尝试将某变量分配给bash

问题描述 投票:1回答:1

我是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

linux bash shell
1个回答
1
投票

除去变量名前面的一些美元符号。在算术上下文中,它们是可选的,即((...))。在分配的左侧,它们不仅是可选的,而且还是被禁止的,因为=需要左侧的变量名而不是其值。

$((...))应为纯((...)),且没有前导美元符号。美元符号将捕获表达式的结果,并尝试将其作为命令运行。它将尝试运行名为05或任何计算值的命令。

您可以写:

((total = $total + $choice))
((count = $count + 1))

或:

((total = total + choice))
((count = count + 1))

甚至:

((total += choice))
((count += 1))
© www.soinside.com 2019 - 2024. All rights reserved.