home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.unix.shell
- Path: sparky!uunet!infonode!ingr!b11!rls.b11.ingr.com!stavast
- From: stavast@rls.b11.ingr.com (Lyle Stavast)
- Subject: Re: Integers in SH
- Message-ID: <1992Dec13.021805.24204@b11.b11.ingr.com>
- Sender: usenet@b11.b11.ingr.com (Usenet Network)
- Reply-To: stavast@rls.b11.ingr.com
- Organization: Intergraph Corp. Huntsville, AL
- References: <6628@falcon.ukc.ac.uk>
- Date: Sun, 13 Dec 1992 02:18:05 GMT
- Lines: 66
-
- In article <6628@falcon.ukc.ac.uk>, bnb@ukc.ac.uk (The Impossible Dreamer) writes:
- |>
- |> The following should tell you if a given string is an positive integer on
- |> not, I have written it as a shell function. If your sh hasn't got shell
- |> functions it shouldn't be too hard to convert it...
- |>
- |> isint()
- |> {
- |> # Shell function to return true if give number is an integer
- |> for a in `echo $1|sed 's/./& /g'`
- |> do
- |> case $a in
- |> 0|1|2|3|4|5|6|7|8|9) ;;
- |> *) # This isn't a number.. so its not an int
- |> return 1 ;;
- |> esac
- |> done
- |> return 0;
- |> }
-
- I found that another possible way to do this is using expr
-
- -------------
- read var
-
- length=`/bin/expr $var : '.*'`
- digits=`/bin/expr $var : '^[0-9]*'`
-
- if [ $digits -eq $length ]
- then
- echo is an integer
- else
- echo is not an integer
- fi
- ----------------
-
- By combining these in an if statement, you can potentially replace the
- (echos , seds , case and for)*variable_length with 2 exprs, 2 variable
- assignments , a test statement and an if.
-
- I am NOT an expr user generally, so there may be some systems this
- doesn't work on and some variable conditions that might cause it to
- fail - I'm just suggesting a way to do the same thing Brian suggests
- with a modification. Your mileage may vary :-)
-
- |>
- |> To use it just put it at the top of your shell script and call it in an if
- |> eg.
- |>
- |> echo -n "Number of lines:"
- |> read a
- |> if isint $a
- |> then
- |> echo OK
- |> else
- |> echo Hows about an integer
- |> fi
- |> --
- |> Brian Blackmore, Darwin College,
- |> The University of Kent at Canterbury, United Kingdom.
-
- --
- +=======================================================================+
- | R. Lyle Stavast stavast@rls.b11.ingr.com (205) 730-5624 |
- +=======================================================================+
-
-