[olug] Test for integer in bash

John Hobbs john at velvetcache.org
Wed Nov 28 22:21:16 UTC 2007


Hello all,

This is kind of a two part question.

First, does anyone know of a better way to test for an integer in bash
than this?


#!/bin/bash

function testInt {
  echo "Testing: $1"
  echo "$1" | grep ^[0-9]*$ > /dev/null

  if [ "$?" -eq 0 ]; then
    echo 'yep, it should be an integer.'
  else
    echo 'nope, dunno what it is.'
  fi
  echo
}

testInt 900
testInt foobar
testInt


Secondly, I'm sure you've noticed that the last test of nothing
returns as a match.  Why can't I get the correct regex,  echo 900 |
grep ^[0-9]+$  , to work?  echo 900 | grep ^[0-9]{1,}$ fails too.

Thanks for taking a look.

- John



More information about the OLUG mailing list