home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / unix / question / 14665 < prev    next >
Encoding:
Internet Message Format  |  1992-12-14  |  1.3 KB

  1. 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
  2. From: net@cs.tu-berlin.de (Oliver Laumann)
  3. Newsgroups: comp.unix.questions
  4. Subject: Re: Integers in SH
  5. Summary: Use expr(1)
  6. Message-ID: <1992Dec14.101533.2543@cs.tu-berlin.de>
  7. Date: 14 Dec 92 10:15:33 GMT
  8. References: <5899@esf.esf.de> <Bz8J1p.52K@ddsw1.mcs.com>
  9. Sender: news@cs.tu-berlin.de
  10. Organization: Technical University of Berlin, Germany
  11. Lines: 29
  12.  
  13. dattier@ddsw1.mcs.com (DWT) writes:
  14. > | does anyone of you out there know how I can make sure that I have read an
  15. > | integer rather than a string?
  16.  
  17. > read a
  18. > case "$a" in
  19. > *[!0-9+-]*|?*[-+]*) echo not an integer ;; # [comment deleted]
  20. > *) echo Now that\'s an integer. ;;
  21. > esac
  22.  
  23. This is not portable; not all versions of /bin/sh (for instance, the
  24. 4.3 BSD shell) support the "!" operator in patterns.  As enumerating
  25. the complement of [0-9] isn't feasible either, I suggest to solve the
  26. problem by means of the "expr" command:
  27.  
  28.     #!/bin/sh
  29.     echo -n "How many: "
  30.     read a
  31.     if [ `expr length $a = $a : "[0-9]*"` = 1 ]; then
  32.     echo Thanks for this fine integer.
  33.     else
  34.     echo Nope, try again.
  35.     fi
  36.  
  37. Note that this solution doesn't correctly handle an empty input; this
  38. can be fixed easily.
  39.  
  40. --
  41. Oliver Laumann    net@cs.tu-berlin.de  net@tub.UUCP  net@tub.BITNET
  42.