1

Is there a way to invert this so that it checks if it is invalid first?

if expr "$string" : '-\?[0-9]\+$' >/dev/null
then
  echo "String is a valid integer."
else
  echo "String is not a valid integer."
fi
2
  • 3
    Did you try if [ ! expr...] ? Commented Aug 8, 2011 at 19:57
  • 3
    You don't need the [ ] to use !. You can type something like ! false right in the shell and see it succeeds. Commented Aug 8, 2011 at 20:00

1 Answer 1

6

Yes, I agree with @nobody and @BenJackson, all you need is to add the 'logical NOT' operator , i.e.

    if ! expr "$string" : '-\?[0-9]\+$' >/dev/null ; then
    #--^  right there ;-)
       echo "String is not a valid integer."
    else
       echo "String is a valid integer."
    fi

I hope this helps.

P.S. as you appear to be a new user, if you get an answer that helps you please remember to mark it as accepted, and/or give it a + (or -) as a useful answer.

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

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.