[olug] Test for integer in bash

Jay Hannah jay at jays.net
Thu Nov 29 14:37:01 UTC 2007


John Hobbs wrote:
> 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
>   

Unless you're intentionally failing negative integers you might want to 
throw an optional - onto the front of your regex.

Cheers,

j


A Perl solution:

$ cat j
900
foobar
-900
$ perl -nle 'print $_, ": ", /^-?\d+$/ ? "yep" : "nope"' j
900: yep
foobar: nope
-900: yep





More information about the OLUG mailing list