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 
Jeff Sloyer
  • 4,899
  • 1
  • 24
  • 48
thisguy
  • 51
  • 1
  • 2

2 Answers2

3

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.

David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
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
fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 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" =~. – thisguy Apr 24 '15 at 16:06
  • 2
    In case you want negative integers just add a -? (optional '-') to the start of the regex as such: [[ ! "$f1" =~ ^-?[0-9]+$ ]] – LinkBerest Apr 24 '15 at 16:07
  • @thisguy this is well explained in [The conditional expression](http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression). Specifically when it talks about ` != ` as ` is checked against the pattern - TRUE on no match`. – fedorqui Apr 24 '15 at 22:22