Reputation: 1277
I'm going to learn bash programming. I just wrote a simple script in order to read numbers from input stream and check them to be in valid numerical format using regular expression. in fact script should take input until the input be nonnumerical. but it doesn't work properly.
code:
i=0
echo "plz enter number in valid format: "
while true
do
read input
if [[ $input =~ *[^0-9]* ]]; then
echo "YOU DIDN'T ENTER A VALID NUMBER"
break
else
arr[$i]=$input
echo $input >> inputnums
fi
done
when i enter a number or character condition is true. I mean i have echo "message" in output.
Upvotes: 1
Views: 304
Reputation: 16039
Remove the *
from the regex:
#!/bin/bash
i=0
echo "plz enter number in valid format: "
while true
do
read input
if [[ $input =~ ^[^0-9]+$ ]]; then
echo "YOU DIDN'T ENTER A VALID NUMBER"
break
else
arr[$i]=$input
echo $input
fi
done
Upvotes: 1
Reputation: 785146
You're mixing shell globing with regex, change your if condition to:
if [[ $input =~ [^0-9] ]]; then
regex should use .*
not *
as used by shell shell glob.
Upvotes: 3