while true; do
read -p 'Number (-99 to quit): '
if ! [[ "$REPLY" =~ ^-?[0-9]+$ ]]; then echo 'Error: Not an integer' >&2
elif (( REPLY == -99 )); then break
elif (( REPLY <= 0 )); then echo 'Error: Need positive integers >0' >&2
printf 'Got "%d", that is number %d\n' "$REPLY" "$(( ++c ))"
This is an infinite loop that is exited when the user enters
-99. Any positive integer response will prompt the code to say
Got "some number" followed by how many valid numbers read so far, whereas a negative integer, zero, or a non-numeric input will give a diagnostic message on standard error. The code uses the variable
REPLY which is the variable written to by
read if not given any other variable name.
The test for correct numeric input is done with matching the response against the regular expression
^-?[0-9]+$. This expression will match if the response is on the form that we expect (an optional dash followed by at least one digit). If it doesn't match, a diagnostic message is issued on standard error.
Up until the first
elif we can not be sure that
$REPLY is an integer. After that, we use
(( ... )) for arithmetic evaluation of the comparisons.
The test for
-99 needs to come before the test for negative integers, as we otherwise would not have any way of exiting the loop.