2

Say you have the user enter in a number 0-3 and want to test it. The most common way seems to be:

[[ $var =~ ^[0-3]$ ]]

But how would you use this with:

test expression

My initial attempt doesn't evaluate correctly, e.g.

read -p "Enter selection [0-3] > "
if test $REPLY == '^[0-3]$' ; then
...

It just evaluates the if statement as false.

2
  • 2
    test command does not support regular expressions. use expr instead: stackoverflow.com/questions/7159441/… Commented Mar 27, 2017 at 4:45
  • test "$var" = 0 || test "$var" = 1 || test "$var" = 2 || test "$var" = 3 && echo okay Commented Mar 27, 2017 at 5:26

2 Answers 2

0

test is equivalent to the [ ] structure, but not to [[ ]], which is an extended version. The regex =~ is only available in the extended test, so for simple test or [ ] you have to pull the regex evaluation from elsewhere.

One fix is grep. This pipeline will catch and print the matches:

echo "$REPLY" | grep '^[0-3]$'

Using test with a string evaluates positively if the string is non-empty. Compare these two:

test "" && echo ok

and

test "a" && echo ok

Knowing this, it's now easy to build a compound test from the both elements.

test "$(echo "$REPLY" | grep '^[0-3]$')"

And this can be applied to the script:

read -p "Enter selection [0-3] > "
if test "$(echo "$REPLY" | grep '^[0-3]$')"; then
    ...
fi
Sign up to request clarification or add additional context in comments.

1 Comment

Cool! This is what I was looking for. Thanks.
0

You can use a regex in Bash like this:

echo -n "Your answer> "
read REPLY
if [[ $REPLY =~ ^[0-9]+$ ]]; then
    echo Numeric
else
    echo Non-numeric
fi

Please check the post Using Bash's regular expressions.

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.