From owner-freebsd-questions@FreeBSD.ORG Sun May 15 21:43:07 2005 Return-Path: Delivered-To: freebsd-questions@freebsd.org Received: from mx1.FreeBSD.org (mx1.freebsd.org [216.136.204.125]) by hub.freebsd.org (Postfix) with ESMTP id 77DB416A4CE for ; Sun, 15 May 2005 21:43:07 +0000 (GMT) Received: from gaia.nimnet.asn.au (nimbin.lnk.telstra.net [139.130.45.143]) by mx1.FreeBSD.org (Postfix) with ESMTP id CF85F43D92 for ; Sun, 15 May 2005 21:43:05 +0000 (GMT) (envelope-from smithi@nimnet.asn.au) Received: from localhost (smithi@localhost) by gaia.nimnet.asn.au (8.8.8/8.8.8R1.4) with ESMTP id HAA23692; Mon, 16 May 2005 07:42:54 +1000 (EST) (envelope-from smithi@nimnet.asn.au) Date: Mon, 16 May 2005 07:42:53 +1000 (EST) From: Ian Smith To: =?ISO-8859-1?Q?Mikko_Ty=F6l=E4j=E4rvi?= In-Reply-To: <20050515133928.F10135@sotec.home> Message-ID: MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=ISO-8859-1 Content-Transfer-Encoding: 8BIT cc: freebsd-questions@freebsd.org Subject: Re: simple? sh problen X-BeenThere: freebsd-questions@freebsd.org X-Mailman-Version: 2.1.1 Precedence: list List-Id: User questions List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Sun, 15 May 2005 21:43:07 -0000 On Sun, 15 May 2005, Mikko Työläjärvi wrote: > On Mon, 16 May 2005, Ian Smith wrote: > > How do I test whether a sh argument is an integer or not, so as to avoid > > failing on a syntax error from otherwise working code such as: > > > > [ $3 -lt 10 -o $3 -gt 600 ] && echo "$0 $1 $2: $3 invalid" && exit 1 > > > > when $3 is a non-integer argument? Do I need to delve into awk and REs, > > or is there something more simple I've missed in mans test, expr, etc? > > Here are some suggestions for functions to do the test: > > isnum() { > expr "$1" : '^[0-9][0-9]*$' >/dev/null > } > > isnum() { > case "$1" in > *[^0-9]*|'') return 1;; > esac > return 0 > } > > The second one is likely to be faster unless "expr" is a shell builtin > (typically it it not). Thanks Mikko; I liked the look of the case version, and it works fine: if ! isnum $3; then echo "$0 $1 $2: $3 is not an integer"; exit 1; fi > $.02, Worth every penny. Cheers, Ian