blob: 50718cc98ad8ddd30675dc577b858c88aee3b9b0 [file] [log] [blame]
Denys Vlasenko74d40582017-08-11 01:32:46 +02001# 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
Denys Vlasenko007ce9f2017-08-13 02:59:00 +020013(
14
Denys Vlasenko74d40582017-08-11 01:32:46 +020015echo "*** no OPTIND, optstring:'ab' args:-a -b c"
16var=QWERTY
17while getopts "ab" var -a -b c; do
18 echo "var:'$var' OPTIND:$OPTIND"
19done
20# unfortunately, "rc:0" is shown since while's overall exitcode is "success"
21echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
22
23# Resetting behavior =1
24echo "*** OPTIND=1, optstring:'ab' args:-a -b c"
25OPTIND=1
26while getopts "ab" var -a -b c; do
27 echo "var:'$var' OPTIND:$OPTIND"
28done
29echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
30
31# Resetting behavior =0
32echo "*** OPTIND=0, optstring:'ab' args:-a -b c"
33OPTIND=0
34while getopts "ab" var -a -b c; do
35 echo "var:'$var' OPTIND:$OPTIND"
36done
37echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
38
39# Resetting behavior "unset"
40echo "*** unset OPTIND, optstring:'ab' args:-a -b c"
41unset OPTIND
42while getopts "ab" var -a -b c; do
43 echo "var:'$var' OPTIND:$OPTIND"
44done
45echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
46
47# What is the final exitcode?
48echo "*** optstring:'ab' args:-a -b c"
49unset OPTIND
50getopts "ab" var -a -b c; echo "1 rc:$? var:'$var' OPTIND:$OPTIND"
51getopts "ab" var -a -b c; echo "2 rc:$? var:'$var' OPTIND:$OPTIND"
52getopts "ab" var -a -b c; echo "3 rc:$? var:'$var' OPTIND:$OPTIND"
53
54# Where would it stop? c or -c?
55echo "*** unset OPTIND, optstring:'ab' args:-a c -c -b d"
56unset OPTIND
57while getopts "ab" var -a c -c -b d; do
58 echo "var:'$var' OPTIND:$OPTIND"
59done
60echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
61
62# What happens on unknown option?
63echo "*** unset OPTIND, optstring:'ab' args:-a -c -b d"
64unset OPTIND
65while getopts "ab" var -a -c -b d; do
66 echo "var:'$var' OPTIND:$OPTIND"
67done
68echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
69
70# ORTERR=0 suppresses error message?
71echo "*** unset OPTIND, OPTERR=0, optstring:'ab' args:-a -c -b d"
72unset OPTIND
73OPTERR=0
74while getopts "ab" var -a -c -b d; do
75 echo "var:'$var' OPTIND:$OPTIND"
76done
77echo "exited: rc:$? var:'$var' OPTIND:$OPTIND"
Denys Vlasenko007ce9f2017-08-13 02:59:00 +020078
79) 2>&1 \
80| sed -e 's/ unrecognized option: / invalid option -- /' \
81 -e 's/ illegal option -- / invalid option -- /' \