home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #30 / NN_1992_30.iso / spool / comp / unix / shell / 5055 < prev    next >
Encoding:
Text File  |  1992-12-14  |  2.2 KB  |  79 lines

  1. Newsgroups: comp.unix.shell
  2. Path: sparky!uunet!infonode!ingr!b11!rls.b11.ingr.com!stavast
  3. From: stavast@rls.b11.ingr.com (Lyle Stavast)
  4. Subject: Re: Integers in SH
  5. Message-ID: <1992Dec13.021805.24204@b11.b11.ingr.com>
  6. Sender: usenet@b11.b11.ingr.com (Usenet Network)
  7. Reply-To: stavast@rls.b11.ingr.com
  8. Organization: Intergraph Corp. Huntsville, AL
  9. References:  <6628@falcon.ukc.ac.uk>
  10. Date: Sun, 13 Dec 1992 02:18:05 GMT
  11. Lines: 66
  12.  
  13. In article <6628@falcon.ukc.ac.uk>, bnb@ukc.ac.uk (The Impossible Dreamer) writes:
  14. |> 
  15. |> The following should tell you if a given string is an positive integer on
  16. |> not, I have written it as a shell function. If your sh hasn't got shell
  17. |> functions it shouldn't be too hard to convert it...
  18. |> 
  19. |> isint()
  20. |> {
  21. |> # Shell function to return true if give number is an integer
  22. |>     for a in `echo $1|sed 's/./& /g'`
  23. |>     do
  24. |>         case $a in
  25. |>             0|1|2|3|4|5|6|7|8|9) ;;
  26. |>             *) # This isn't a number.. so its not an int
  27. |>             return 1 ;;
  28. |>         esac
  29. |>     done
  30. |>     return 0;
  31. |> }
  32.  
  33. I found that another possible way to do this is using expr 
  34.  
  35. -------------
  36. read var
  37.  
  38. length=`/bin/expr $var : '.*'`
  39. digits=`/bin/expr $var : '^[0-9]*'`
  40.  
  41. if [ $digits -eq $length ]
  42. then
  43.     echo is an integer
  44. else
  45.     echo is not an integer
  46. fi
  47. ----------------
  48.  
  49. By combining these in an if statement, you can potentially replace the
  50. (echos , seds , case and for)*variable_length with 2 exprs, 2 variable
  51. assignments , a test statement and an if.
  52.  
  53. I am NOT an expr user generally, so there may be some systems this
  54. doesn't work on and some variable conditions that might cause it to
  55. fail - I'm just suggesting a way to do the same thing Brian suggests
  56. with a modification.   Your mileage may vary :-)
  57.  
  58. |> 
  59. |> To use it just put it at the top of your shell script and call it in an if
  60. |> eg.
  61. |> 
  62. |> echo -n "Number of lines:"
  63. |> read a
  64. |> if isint $a
  65. |> then
  66. |>     echo OK
  67. |> else
  68. |>     echo Hows about an integer
  69. |> fi
  70. |> --
  71. |> Brian Blackmore, Darwin College,
  72. |> The University of Kent at Canterbury, United Kingdom.
  73.  
  74. -- 
  75. +=======================================================================+
  76. |      R. Lyle Stavast  stavast@rls.b11.ingr.com (205) 730-5624         |
  77. +=======================================================================+
  78.  
  79.