That if [ read = null ]
line is nonsense. It doesn't make any sense at all.
You're using bash, so you can read the numbers into an array, rather than a fixed number of variables.
Try something like this:
$ cat add.sh
#!/bin/bash
while true; do
printf "Please input numbers to add: "
read -r -a numbers
exit if input is empty
[ "${#numbers[@]}" == 0 ] && break
check if input consists only of numbers
(integers or decimals allowed)
for n in "${numbers[@]}"; do
if ! [[ "$n" =~ ^[0-9]+(.[0-9]+)?$ ]] ; then
echo "Invalid input: $n"
continue 2
fi
done
expression="$(printf "%s+" "${numbers[@]}" | sed -e 's/+$//')"
echo "$expression" | bc
done
This loops forever (while true
), asks for input and reads the input into array numbers
.
If the number of elements in numbers
is zero, it exits the while loop with break
. BTW, "${#numbers[@]}"
returns the number of elements in the array - i.e. the "word count" you want. You can just print this with echo
or printf
if you want. I'm not going to do all of your homework for you, so I'll leave that for you to do.
If any of the input elements isn't a number, it prints "Invalid input" and returns to the beginning of the while loop (with continue 2
- the 2
argument is necessary because at this point the script is inside a while
loop and a for
loop. Without the 2
, it would only exit the for
loop, i.e. it would print "Invalid input" and then try to perform the calculation)
Otherwise it constructs a string (in a variable called expression
) using printf
. sed
is used to strip the trailing +
from the end of the string.
Then it pipes the expression into bc, which is a calculator tool. Unlike bash's built-in integer-only arithmetic, bc
can handle floating point numbers. bc
may not be installed by default on your system, but if you're running Linux, it should be available as a package (e.g. on Debian, it's in the bc
package). It's part of the POSIX spec, so should be available for other unix variants too, see https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html
$ ./add.sh
Please input numbers to add: 1 2 3
6
Please input numbers to add: 1 2 3 xyz
Invalid input: xyz
Please input numbers to add: 4 5 6 7 8 9
39
Please input numbers to add:
In this example run, the first input line is turned into the expression 1+2+3
and then piped into bc
to perform the calculation. The third input line is turned into 4+5+6+7+8+9
and piped into bc
.
https://shellcheck.net
, a syntax checker, or installshellcheck
locally. Make usingshellcheck
part of your development process. – waltinator Nov 29 '21 at 03:48