Reputation: 95
I have the following variable with a list of numbers
vlist="1 13 20 21 22 24 25 28 240 131 133 136 138 224"
In the next loop I want to input a number between 1 - 250 except the numbers in vlist
while :; do
echo -en 'Number : ' ; read -n3 cvip ; echo
[[ $cvip =~ ^[0-9]+$ ]] || { echo -e '\nSorry input a number between 1 and 239 except '$vlist'\n' ; continue; }
cvip=$(expr ${cvip} + 0)
if ((cvip >= 1 && cvip <= 250)); then break ; else echo -e '\nNumber out of Range, input a number between 1 and 239 except '$vlist'\n' ; fi
done
Ηow can I enter the list exception inside the if statement range
Upvotes: 0
Views: 62
Reputation: 52449
If using bash
, one approach is to store the bad numbers as keys in an associative array and see if that particular key exists when validating a number:
#!/usr/bin/env bash
vlist="1 13 20 21 22 24 25 28 240 131 133 136 138 224"
declare -A nums
for num in $vlist; do
nums[$num]=1
done
while true; do
while read -p "Number: " -r num; do
if [[ ! $num =~ ^[[:digit:]]+$ ]]; then
echo "Input an integer."
elif [[ ${nums[$num]:-0} -eq 1 ]]; then
echo "Input a number between 1 and 250 except '$vlist'"
elif [[ $num -lt 1 || $num -gt 250 ]]; then
echo "Input an integer between 1 and 250"
else
break
fi
done
printf "You successfully inputted %d\n" "$num"
done
The important bit is ${nums[$num]:-0}
, which expands to the value of that element of the associative array if that key exists and is not null, or 0 otherwise. As noted by Glenn in a comment, in bash
4.3 or newer, [[ -v nums[$num] ]]
works too for testing to see if a given key exists, so [[ ${nums[$num]:-0} -eq 1 ]]
in the above could be replaced with it.
Upvotes: 1