getopt_simple.tests 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. # Simple usage cases for getopts.
  2. #
  3. # OPTIND is either not touched at all (first loop with getopts,
  4. # relying on shell startup init), or getopts state is reset
  5. # before new loop with "unset OPTIND", "OPTIND=1" or "OPTIND=0".
  6. #
  7. # Each option is a separate argument (no "-abc"). This conceptually
  8. # needs only $OPTIND to hold getopts state.
  9. #
  10. # We check that loop does not stop on unknown option (sets "?"),
  11. # stops on _first_ non-option argument.
  12. echo "*** no OPTIND, optstring:'ab' args:-a -b c"
  13. var=QWERTY
  14. while getopts "ab" var -a -b c; do
  15. echo "var:'$var' OPTIND:$OPTIND"
  16. done
  17. # unfortunately, "rc:0" is shown since while's overall exitcode is "success"
  18. echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
  19. # Resetting behavior =1
  20. echo "*** OPTIND=1, optstring:'ab' args:-a -b c"
  21. OPTIND=1
  22. while getopts "ab" var -a -b c; do
  23. echo "var:'$var' OPTIND:$OPTIND"
  24. done
  25. echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
  26. # Resetting behavior =0
  27. echo "*** OPTIND=0, optstring:'ab' args:-a -b c"
  28. OPTIND=0
  29. while getopts "ab" var -a -b c; do
  30. echo "var:'$var' OPTIND:$OPTIND"
  31. done
  32. echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
  33. # Resetting behavior "unset"
  34. echo "*** unset OPTIND, optstring:'ab' args:-a -b c"
  35. unset OPTIND
  36. while getopts "ab" var -a -b c; do
  37. echo "var:'$var' OPTIND:$OPTIND"
  38. done
  39. echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
  40. # What is the final exitcode?
  41. echo "*** optstring:'ab' args:-a -b c"
  42. unset OPTIND
  43. getopts "ab" var -a -b c; echo "1 rc:$? var:'$var' OPTIND:$OPTIND"
  44. getopts "ab" var -a -b c; echo "2 rc:$? var:'$var' OPTIND:$OPTIND"
  45. getopts "ab" var -a -b c; echo "3 rc:$? var:'$var' OPTIND:$OPTIND"
  46. # Where would it stop? c or -c?
  47. echo "*** unset OPTIND, optstring:'ab' args:-a c -c -b d"
  48. unset OPTIND
  49. while getopts "ab" var -a c -c -b d; do
  50. echo "var:'$var' OPTIND:$OPTIND"
  51. done
  52. echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
  53. # What happens on unknown option?
  54. echo "*** unset OPTIND, optstring:'ab' args:-a -c -b d"
  55. unset OPTIND
  56. while getopts "ab" var -a -c -b d; do
  57. echo "var:'$var' OPTIND:$OPTIND"
  58. done
  59. echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
  60. # ORTERR=0 suppresses error message?
  61. echo "*** unset OPTIND, OPTERR=0, optstring:'ab' args:-a -c -b d"
  62. unset OPTIND
  63. OPTERR=0
  64. while getopts "ab" var -a -c -b d; do
  65. echo "var:'$var' OPTIND:$OPTIND"
  66. done
  67. echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"