[olug] Test for integer in bash

John Hobbs john at velvetcache.org
Thu Nov 29 16:06:02 UTC 2007


I like that one, much less code there.

And @ Jay Hannah, I am chucking negatives :)

On 11/29/07, Sean Kelly <smkelly at zombie.org> wrote:
> On Wed, Nov 28, 2007 at 04:21:16PM -0600, John Hobbs wrote:
> > 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?
>
> How about something like:
>
> if [ "$1" -eq "$1" ] 2>/dev/null; then
>      echo "True"
> else
>      echo "False"
> fi
>
> The -eq test seems to only like integers and throws an error if fed
> something else:
>      spiderpig:~ smkelly$ if [ "moo" -eq "moo" ]; then echo "True"; else echo "False"; fi-
>      bash: [: moo: integer expression expected
>      False
>
> So, if you throw the 2>/dev/null in there, it will eliminate the error from
> bash and execute the 'else' clause. I also tested this with /bin/sh in
> FreeBSD and it works with that, too. It also returns false on floats.
>
> --
> Sean Kelly          | PGP KeyID: D2E5E296
> smkelly at smkelly.org | http://www.smkelly.org
> _______________________________________________
> OLUG mailing list
> OLUG at olug.org
> http://lists.olug.org/mailman/listinfo/olug
>



More information about the OLUG mailing list