I would like to check in a while loop that the value entered into a variable is a number and that the number is between 1 and 5.
I'm trying this, but it doesn't work:
#!/bin/bash
# Ejercicio 7
while [[ $( grep -vE "[1-5]" $OPTION ) || $OPTION -lt 1 || $OPTION -gt 5 ]]
do
echo "Escoche la operación:"
echo "1. Sumar"
echo "2. Restar"
echo "3. Multiplicar"
echo "4. Dividir"
echo "5. salir"
read OPTION
done
To validate if the variable is a number you can say:
To validate that the number is between 1 and 5 you would say:
The first time you are validating the value of "$OPTION" before giving it any data. What would work well is something like a do_while, which you can express like this, negating the above expression so that it keeps reading while the value is invalid:
First of all, as far as I understand,
bash
you don't have such a thing as "variables by type" - everything is a string. I have no way to prove it but it is as far as I understand. I say this because checking if a variable is a number or not, would depend on a strategy on certain characters, instead of asking for something like "a type (int, str, varchar, class, etc)".Now, an option that I give you is to use a kind of
while-do
(it does not exist by default inbash
, but it can be implemented) and a simple regular expression to do everything at the same time (both checking if it is a number and knowing if it is between 1 and 5 ) and exit if it is 5.Clarification about the regular expression.
The regular expression
^[1-5]$
is a simple way to know if a string meets the pattern: starts with (this indicates that it starts at the beginning of the line:^
) a single element of the list [12345] (with [1-5] which is a range inclusive), and then terminates (this indicates that it terminates at the end of the line:$
). That is: a single number between 1 and 5.So far you can copy and paste the above.
A bit sophisticated and unnecessary version, but very illustrative.
With the use of a
select
.In this case, instead of using a
while
, I propose the use ofselect
thebash
.