5

I'm trying to write an if statement in bash that will exit if the variable supplied is not an integer. I will eventually be nesting this if statement within a while loop.

When I do run this I am getting an syntax error.

#!/bin/bash
if [ $f1 != ^[0-9]+$ ]
    then 
        exit 1 
    fi 
1
  • 1
    by integer, are you including negative integers or only positive? Commented Apr 24, 2015 at 15:50

2 Answers 2

5

I have always like the integer test using the equality test construct:

[ $var -eq $var 2>/dev/null ] || exit 1

If var is not an integer, the equality fails due to the error generated. It is also POSIX compliant as it doesn't rely on character classes or the bash [[ construct.

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

Comments

2

You better negate the condition like this:

if [[ ! "$f1" =~ ^[0-9]+$ ]]; then 
  exit 1
fi

note the [[ and ]] syntax for the regular expressions, together with ! to negate it. Then, we use =~ for regexs.

Test

$ r=23a
$ [[ ! "$r" =~ ^[0-9]+$ ]] && echo "no digit" || echo "digit"
no digit
$ r=23
$ [[ ! "$r" =~ ^[0-9]+$ ]] && echo "no digit" || echo "digit"
digit

3 Comments

thank you very much can you explain to me why this is important and what this command do to make this work correctly ? note the [[ and ]] syntax, together with ! "$var" =~.
In case you want negative integers just add a -? (optional '-') to the start of the regex as such: [[ ! "$f1" =~ ^-?[0-9]+$ ]]
@thisguy this is well explained in The conditional expression. Specifically when it talks about <STRING> != <PATTERN> as <STRING> is checked against the pattern <PATTERN> - TRUE on no match.

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.