0

im trying to do a Number Check not including decimals as well as within range check but it is not working

example of accepted numbers: 1, 10, 100
not accepted numbers: 1.1, 10.1, 100.1



echo "Qty Sold: "
read sold 
if [[ "$sold" =~ `^([0-9])$` && "$sold" -gt 0 && "$sold" -lt 999 ]] ;
then    
echo "ok"   
else     
echo "Error, Qty Sold Must be Positive Integer";
fi

3 Answers 3

2

Remove the backticks which exists around your regex and use + after [0-9] to match one or more digits.

if [[ "$sold" =~ ^[0-9]+$ && "$sold" -gt 0 && "$sold" -lt 999 ]] ;

Example:

$ sold=12
$ if [[ "$sold" =~ ^[0-9]+$ && "$sold" -gt 0 && "$sold" -lt 999 ]] ; then echo 'Ok'; else echo 'NOT ok'; fi
Ok
$ sold=0
$ if [[ "$sold" =~ ^[0-9]+$ && "$sold" -gt 0 && "$sold" -lt 999 ]] ; then echo 'Ok'; else echo 'NOT ok'; fi
NOT ok
$ sold=1000
$ if [[ "$sold" =~ ^[0-9]+$ && "$sold" -gt 0 && "$sold" -lt 999 ]] ; then echo 'Ok'; else echo 'NOT ok'; fi
NOT ok
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! forgot about the +
1

Without using regex:

((sold>0 && sold <999)) 2>/dev/null && echo "ok" || echo "Error, Qty Sold Must be Positive Integer"

Comments

0

The [[ syntax is a bit different from [ syntax. You do not need any delimiter around the regex in =~. So no / or backtick or apostrophe or ampersand is needed (only if regex contains a space. It can be escaped by backslash or add apostrophe or ampersand around the space or use [[:space:]] instead (which also includes TAB and some other whitespace characters)). What is more the ampersand also not needed around $sold (only in [[!). So the conditional part may be like this

if [[ $sold =~ ^[[:digit:]]{1,3}$ && $sold -gt 0 && $sold -lt 999 ]]; then echo ok
else  echo "Error, Qty Sold Must be Positive Integer between 1 and 998";
fi

This checks if one, two or three digits are entered and it is not zero.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.