[NTLUG:Discuss] basic Bash question
Steve Baker
sjbaker1 at airmail.net
Tue Aug 3 18:31:59 CDT 2004
Lance Simmons wrote:
> Is there a simple way in a bash script to test whether a string is an
> integer?
Hmmm - tricky.
Well, I can think of a kinda-sorta way.
#!/bin/bash
XXX=$1
YYY="WibbleWibble"
let YYY=$XXX+0 >& /dev/null
if [[ $YYY == $XXX ]] ; then echo "INTEGER" ; else echo "NOT INTEGER" ; fi
($1 is your string to be tested)
The 'let' statement forces XXX to be treated as an integer. If it really
is an integer then YYY will be equal to it. If it's not an integer then
YYY will be left as "WibbleWibble" and YYY and XXX will be different.
The only snag that I know of is that your integer has to have no leading
zeroes. (My script will say 0123 is not an integer) Also, the string
"WibbleWibble" must never show up as a valid value for your string.
---------------------------- Steve Baker -------------------------
HomeEmail: <sjbaker1 at airmail.net> WorkEmail: <sjbaker at link.com>
HomePage : http://www.sjbaker.org
Projects : http://plib.sf.net http://tuxaqfh.sf.net
http://tuxkart.sf.net http://prettypoly.sf.net
-----BEGIN GEEK CODE BLOCK-----
GCS d-- s:+ a+ C++++$ UL+++$ P--- L++++$ E--- W+++ N o+ K? w--- !O M-
V-- PS++ PE- Y-- PGP-- t+ 5 X R+++ tv b++ DI++ D G+ e++ h--(-) r+++ y++++
-----END GEEK CODE BLOCK-----
More information about the Discuss
mailing list