shell dot on steroids https://pagure.io/shellfu

types.sh 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/bin/bash
  2. ffoo import core
  3. is_integer() {
  4. #
  5. # True if $1 is integer value
  6. #
  7. # This is achieved by checking if
  8. #
  9. local val="$1"
  10. test 0 -ge "$val" 2>/dev/null || test 0 -le "$val" 2>/dev/null
  11. case $? in
  12. 0) return 0 ;;
  13. 2) return 1 ;;
  14. *) warn "weird exit status in is_integer()"; return 2 ;;
  15. esac
  16. }
  17. bool() {
  18. #
  19. # True if $1 is true
  20. #
  21. # bool [--like-sh|--like-c] value
  22. #
  23. # Returns with zero exit status for $1 values of "true",
  24. # "yes" or "y", 1 for for "false", "no" or "n" (only common
  25. # English is supported). For any other non-integer value,
  26. # prints warning and exits with status of 2.
  27. #
  28. # For integer values, if --like-sh is specified (default),
  29. # zero produces zero, but any other value produces 1. Use
  30. # --like-c to turn this logic around, i.e. as C works:
  31. # anything else than zero is considered true, resulting in
  32. # zero exit status.
  33. #
  34. local mode=sh
  35. while true; do case "$1" in
  36. --like-sh) mode=sh; shift ;;
  37. --like-c) mode=c; shift ;;
  38. *) break ;;
  39. esac done
  40. local value="$1"
  41. local reset_shopt="$(shopt -p)"
  42. debug -v value
  43. if is_integer "$value";
  44. then
  45. case "$mode:$value" in
  46. c:0) return 1 ;;
  47. c:*) return 0 ;;
  48. sh:0) return 0 ;;
  49. sh:[0-9]*) return 1 ;; # positive bash exit status
  50. *) warn "unexpected 'mode:value': $mode:$value"; return 2 ;;
  51. esac
  52. else
  53. case "${value,,}" in
  54. true|yes|y) return 0 ;;
  55. false|no|n) return 1 ;;
  56. "") usage_is -E "[-n] value"; return 2 ;;
  57. *) warn "cannot determine true-ness: $value"; return 2 ;;
  58. esac
  59. fi
  60. }