home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!noc.near.net!hri.com!spool.mu.edu!yale.edu!ira.uka.de!math.fu-berlin.de!mailgzrz.TU-Berlin.DE!cs.tu-berlin.de!net
- From: net@cs.tu-berlin.de (Oliver Laumann)
- Newsgroups: comp.unix.questions
- Subject: Re: Integers in SH
- Summary: Use expr(1)
- Message-ID: <1992Dec14.101533.2543@cs.tu-berlin.de>
- Date: 14 Dec 92 10:15:33 GMT
- References: <5899@esf.esf.de> <Bz8J1p.52K@ddsw1.mcs.com>
- Sender: news@cs.tu-berlin.de
- Organization: Technical University of Berlin, Germany
- Lines: 29
-
- dattier@ddsw1.mcs.com (DWT) writes:
- > | does anyone of you out there know how I can make sure that I have read an
- > | integer rather than a string?
-
- > read a
- > case "$a" in
- > *[!0-9+-]*|?*[-+]*) echo not an integer ;; # [comment deleted]
- > *) echo Now that\'s an integer. ;;
- > esac
-
- This is not portable; not all versions of /bin/sh (for instance, the
- 4.3 BSD shell) support the "!" operator in patterns. As enumerating
- the complement of [0-9] isn't feasible either, I suggest to solve the
- problem by means of the "expr" command:
-
- #!/bin/sh
- echo -n "How many: "
- read a
- if [ `expr length $a = $a : "[0-9]*"` = 1 ]; then
- echo Thanks for this fine integer.
- else
- echo Nope, try again.
- fi
-
- Note that this solution doesn't correctly handle an empty input; this
- can be fixed easily.
-
- --
- Oliver Laumann net@cs.tu-berlin.de net@tub.UUCP net@tub.BITNET
-