I've just started programming shell script on my school and I've come over some problems I can't find answers on.
I have a school assignment to make a shell script where a user are supposed to type a number + enter and repeat this until the user types ctrl+d, then the program should echo the sum and the program should end.
This is the script I wrote.
sum=0
while [ true ]
do
read number
sum=$(($sum+$number))
done
function finish {
echo "Sum: $sum"
}
trap finish exit
Running the script in my terminal it looks like this:
4
5
summer.sh: line 5: 9+: syntax error: operand expected (error token is "+")
Sum: 9
I read How can I add numbers in a bash script and thought I used the arithmetic expression correct (it even displays the right sum), but nevertheless I tried another suggestion from the same question. I changed it to:
sum=$((sum+number))
Now I don't get the syntax error. But I can't terminate the program by typing ctrl-d. Example of running code now:
4
5
^D
^C
What happened? Why does a change in the arithmetic expression in the script affect the behaviour of ctrl-d?