Check for valid number in busybox?
-
11-04-2021 - |
Question
I am trying to do a script where i need to check if the user input is valid. I just can't figure it out. Have been trying different ways but can't find a solution. So if there are a busybox ash guru out there i am happy for all help.
if ! [[ $ANS =~ ^[0-9][.0-9]*$ ]]; then
echo "abort"
else
echo "go on"
fi
I want to see if the user inputs a number. A number with decimal is also allowed. If not then it should abort.
Same goes with..
if ! [[ $ANS =~ ^[0-9A-Fa-f]{6}$ ]] ; then
echo "abort"
else
echo "go on"
fi
Where i need it to see if hexadecimal is used. All i get is "unknown operand".
Solution
It feels a bit of a hack, but you can use egrep
for this:
$ ANS=10.2
$ echo -n $ANS | egrep -q '^[0-9]*[.]?[0-9]*$' && echo success || echo failure
success
$ ANS=10.2.2
$ echo -n $ANS | egrep -q '^[0-9]*[.]?[0-9]*$' && echo success || echo failure
failure
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow