Reputation: 3
I'm trying to write a short shell script that lets me input a bunch of numbers, each followed by ENTER, and then use CTRL+D to stop taking input and to print the sum of the inputted numbers.
The result I'm looking for is something like this:
sum.sh
1 [ENTER]
5 [ENTER]
8 [ENTER]
[CTRL+D]
14
I have a vague idea that I can do this using read and keycodes, but I haven't been able to figure it out.
Upvotes: 0
Views: 798
Reputation: 23850
You can use read -r VARNAME
for that, e.g.:
#!/bin/bash
sum=0
while read -r n; do
((sum += n))
done
echo "$sum"
Upvotes: 3