[olug] Test for integer in bash
Sean Kelly
smkelly at zombie.org
Thu Nov 29 11:05:14 UTC 2007
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
More information about the OLUG
mailing list