Hi I have a menu on a bash script. The user must enter a number between 1 and 5. This is my code:
read -r data
while [[ ${data} -lt 1 ]] || [[ ${data} -gt 5 ]]; do
echo "You must enter a number between 1 and 5"
read -r data
done
At first sight is working fine, but the problem happens is if the user enter a "*" or a "/" (and maybe other special chars). They break the script because of a syntactical error. I guess this is "some kind of injection".
How can I do to avoid this "breaking inputs" and keep my data as a number between 1 and 5? Maybe a combination of regex and this? How? Thank you.
EDIT The use of a case is not valid for me. For the minimal example I put static numbers but the reality is that 1 and 5 are dynamic numbers so it can't be done using a static case.
Just add a condition checking for digits: [[ $data =~ ^[[:digit:]]+$ ]]
read -r data
while [[ ! $data =~ ^[[:digit:]]+$ ]] || (( data < 1 || data > 5 )); do
echo "You must enter a number between 1 and 5"
read -r data
done