]>
Commit | Line | Data |
---|---|---|
2b6fc908 KZ |
1 | #!/bin/bash |
2 | ||
d27f5fe7 SK |
3 | # A small example script for using the getopt(1) program. |
4 | # This script will only work with bash(1). | |
5 | # A similar script using the tcsh(1) language can be found | |
1ab5f9b7 | 6 | # as getopt-example.tcsh. |
2b6fc908 KZ |
7 | |
8 | # Example input and output (from the bash prompt): | |
d27f5fe7 | 9 | # |
1ab5f9b7 | 10 | # ./getopt-example.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long " |
2b6fc908 KZ |
11 | # Option a |
12 | # Option c, no argument | |
d27f5fe7 SK |
13 | # Option c, argument 'more' |
14 | # Option b, argument ' very long ' | |
2b6fc908 | 15 | # Remaining arguments: |
d27f5fe7 SK |
16 | # --> 'par1' |
17 | # --> 'another arg' | |
18 | # --> 'wow!*\?' | |
2b6fc908 | 19 | |
d27f5fe7 SK |
20 | # Note that we use "$@" to let each command-line parameter expand to a |
21 | # separate word. The quotes around "$@" are essential! | |
22 | # We need TEMP as the 'eval set --' would nuke the return value of getopt. | |
9ac755f6 | 23 | TEMP=$(getopt -o 'ab:c::' --long 'a-long,b-long:,c-long::' -n 'example.bash' -- "$@") |
2b6fc908 | 24 | |
d27f5fe7 SK |
25 | if [ $? -ne 0 ]; then |
26 | echo 'Terminating...' >&2 | |
27 | exit 1 | |
28 | fi | |
2b6fc908 | 29 | |
d27f5fe7 | 30 | # Note the quotes around "$TEMP": they are essential! |
2b6fc908 | 31 | eval set -- "$TEMP" |
d27f5fe7 | 32 | unset TEMP |
2b6fc908 | 33 | |
d27f5fe7 | 34 | while true; do |
2b6fc908 | 35 | case "$1" in |
d27f5fe7 SK |
36 | '-a'|'--a-long') |
37 | echo 'Option a' | |
38 | shift | |
39 | continue | |
40 | ;; | |
41 | '-b'|'--b-long') | |
42 | echo "Option b, argument '$2'" | |
43 | shift 2 | |
44 | continue | |
45 | ;; | |
46 | '-c'|'--c-long') | |
2b6fc908 KZ |
47 | # c has an optional argument. As we are in quoted mode, |
48 | # an empty parameter will be generated if its optional | |
49 | # argument is not found. | |
50 | case "$2" in | |
d27f5fe7 SK |
51 | '') |
52 | echo 'Option c, no argument' | |
53 | ;; | |
54 | *) | |
55 | echo "Option c, argument '$2'" | |
56 | ;; | |
57 | esac | |
58 | shift 2 | |
59 | continue | |
60 | ;; | |
61 | '--') | |
62 | shift | |
63 | break | |
64 | ;; | |
65 | *) | |
66 | echo 'Internal error!' >&2 | |
67 | exit 1 | |
68 | ;; | |
2b6fc908 KZ |
69 | esac |
70 | done | |
d27f5fe7 SK |
71 | |
72 | echo 'Remaining arguments:' | |
73 | for arg; do | |
74 | echo "--> '$arg'" | |
75 | done |