I can't think of a good reason to do this (except perhaps as a homework exercise), but yes, in bash, you can "add variables in a while loop using read". In particular, man bash
notes of the +=
operator:
In the context where an assignment statement is assigning a value to a
shell variable or array index, the += operator can be used to append to
or add to the variable's previous value.
.
.
. When ap‐
plied to a string-valued variable, value is expanded and appended to
the variable's value.
So for example:
#!/bin/bash
declare +i password_input=""
while IFS= read -s -r -n 1 c; do
case $c in
\*) break
;;
*) password_input+=$c
;;
esac
done
The -n 1
arguments allow you to read single characters rather than whole lines. Unsetting the IFS
variable allows the input to contain characters that would otherwise be consumed by field splitting (which may or may not be a good idea in the case of the default IFS - should passwords be allowed to contain whitespace?).
The explicit +i
declaration doesn't seem to be required even if the user enters a wholly numeric sequence, but it makes it clear that the intent is to append rather than sum.
FYI the bash syntax for testing string equality is [[ $str1 == $str2 ]]
.