1

I am trying to validate user input

if ! [[ "$operator" =~ ("[+-/*]") ]] ; then     # validate user input to include decimals
        exec >&2; echo "error: Not a valid number, please try again";
        echo
else
        break
        echo
fi

Tried numerous combinations and not working? Ypu help would be greatly appreciated!

1
  • 2
    Do you want to accept numbers, as the comment and output imply, or operators, as the regex implies? Commented Jan 20, 2013 at 14:58

3 Answers 3

3

Two problems:

  • Lose the quotes and parentheses around the regex; they're considered part of the regex. The quotes around $operator aren't needed either in this context, though they do no harm.
  • - is a special character within [], for use in stuff like a-z. Put it as first or last character to work around this.

So:

if ! [[ $operator =~ [-+/*] ]] ; then

I think it's customary to write ! inside the [[ ]], but either works.

Sign up to request clarification or add additional context in comments.

1 Comment

The ! Negation outside the [[ ]] negates everything inside them eg ! [[ -d file || -r file ]] is different to [[ ! -d file || -r file ]]
0
if ! [[ "$operator" =~ [-+]?[0-9]* ]] ; then
  ...
  ...
fi

Comments

0
sgeorge-mn:~ sgeorge$ cat validate.sh 
OPERATOR=$1
REGEX='[+*-/]';
if ! [[ $OPERATOR =~ $REGEX ]]; then
        echo "Not valid input"
else
        echo "Valid input"
fi

sgeorge-mn:~ sgeorge$ bash validate.sh '-'
Valid input

sgeorge-mn:~ sgeorge$ bash validate.sh '*'
Valid input

sgeorge-mn:~ sgeorge$ bash validate.sh '/'
Valid input

sgeorge-mn:~ sgeorge$ bash validate.sh '+'
Valid input

sgeorge-mn:~ sgeorge$ bash validate.sh 's'
Not valid input

sgeorge-mn:~ sgeorge$ bash validate.sh '132'
Not valid input

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.