Foxtrod89

C:UsersLoverDesktopWickedCoolShellScripts2e_resources_updated15-validint (Lover workspace for Sublime 3) - Sublime Text

Mar 23rd, 2020
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.51 KB | None | 0 0
  1. #!/bin/bash
  2. # validint--Validates integer input, allowing negative ints too.
  3.  
  4. validint()
  5. {
  6. # Validate first field and test that value against min value $2 and/or
  7. # max value $3 if they are supplied: If the value isn't within range or
  8. # it's not composed of just digits, fail.
  9.  
  10. number="$1"; min="$2"; max="$3"
  11.  
  12. if [ -z $number ] ; then
  13. echo "You didn't enter anything. Please enter a number." >&2 ; return 1
  14. fi
  15.  
  16. # Is the first character a '-' sign?
  17. if [ "${number%${number#?}}" = "-" ] ; then
  18. testvalue="${number#?}" # Grab all but the first character to test.
  19. else
  20. testvalue="$number"
  21. fi
  22.  
  23. # Create a version of the number that has no digits, for testing.
  24. nodigits="$(echo $testvalue | sed 's/[[:digit:]]//g')"
  25.  
  26. # Check for non-digit characters.
  27. if [ ! -z $nodigits ] ; then
  28. echo "Invalid number format! Only digits, no commas, spaces, etc" >&2
  29. return 1
  30. fi
  31.  
  32. if [ ! -z $min ] ; then
  33. # Is the input less than the minimum value?
  34. if [ "$number" -lt "$min" ] ; then
  35. echo "$number is too small: smallest acceptable value is $min" >&2
  36. return 1
  37. fi
  38. fi
  39. if [ ! -z $max ] ; then
  40. # Is the input greater than the maximum value?
  41. if [ "$number" -gt "$max" ] ; then
  42. echo "Your value is too big: largest acceptable value is $max" >&2
  43. return 1
  44. fi
  45. fi
  46. return 0
  47. }
  48.  
  49. # Input validation
  50. #if validint "$1" "$2" "$3" ; then
  51. # echo "That input is a valid integer value within your constraints"
  52. #fi
Add Comment
Please, Sign In to add comment