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