home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #1 / NN_1993_1.iso / spool / comp / unix / shell / 5249 < prev    next >
Encoding:
Text File  |  1993-01-05  |  1.4 KB  |  52 lines

  1. Newsgroups: comp.unix.shell
  2. Path: sparky!uunet!munnari.oz.au!yarrina.connect.com.au!warrane.connect.com.au!g2syd!georgeq
  3. From: georgeq@g2syd.genasys.com.au (George Quinlan)
  4. Subject: Re: testing if an arg is a number
  5. Message-ID: <1993Jan5.065746.15541@g2syd.genasys.com.au>
  6. Organization: Genasys II, Sydney, Australia
  7. References: <1hruvtINNbap@sam.ksu.ksu.edu> <6077@sixhub.UUCP>
  8. Date: Tue, 5 Jan 1993 06:57:46 GMT
  9. Lines: 41
  10.  
  11. In article <6077@sixhub.UUCP> davidsen@sixhub.UUCP (bill davidsen) writes:
  12. >In article <1hruvtINNbap@sam.ksu.ksu.edu> dudley@sam.ksu.ksu.edu (D U D L E Y) writes:
  13. >| Was curious, and didn't see it in the FAQ...how would you identify if an
  14. >| argument to a script is *entirely* numeric?
  15. >| 
  16. >| So "12" would return true while "12a" would return false.
  17. >| 
  18. >| The only way I found was to use egrep.
  19. >
  20. >See also expr.
  21. >
  22. >  expr "$n" : "^[0-9][0-9]*$" > /dev/null && echo numeric || echo other
  23. >
  24.  
  25. I was recently asked a similar question and offered this solution:
  26.  
  27. #!/bin/sh
  28.  
  29. isnum()
  30. {
  31.     echo $1 \
  32.     | awk '\
  33.     {
  34.         num = $1 + 0;
  35.  
  36.         if (num == $1)
  37.             exit(0);
  38.         else
  39.             exit(1);
  40.     }'
  41.     return $?
  42. }
  43.  
  44. isnum $1 && echo "numeric" || echo "not numeric"
  45.  
  46. It has the advantage that it recognises valid floating point numbers
  47. (including those in exponential format) as well as integers.
  48. -- 
  49. George Quinlan               Genasys II, 33 Berry St, North Sydney, Australia.
  50. What is the difference between ignorance and apathy?
  51. I don't know, and I don't care.
  52.