update repository
[cmdllinux.git] / bash_n_examples / bash / getopts / getopt-parse2.bash
blobc06375218c8ce9566ec7838041160bbada588030
1 #!/bin/bash
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
6 # as getopt-parse.tcsh.
8 # Example input and output (from the bash prompt):
10 # ./getopt-parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
11 # Option a
12 # Option c, no argument
13 # Option c, argument 'more'
14 # Option b, argument ' very long '
15 # Remaining arguments:
16 # --> 'par1'
17 # --> 'another arg'
18 # --> 'wow!*\?'
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.
23 TEMP=$(getopt -o 'ab:c::' --long '-long,b-long:,c-long::' -n 'example.bash' -- "$@")
25 if [ $? -ne 0 ]; then
26 echo 'Terminating...' >&2
27 exit 1
30 echo "$TEMP"
31 # Note the quotes around "$TEMP": they are essential!
32 eval set -- "$TEMP"
33 unset TEMP
35 while true; do
36 case "$1" in
37 '-a'|'--a-long')
38 echo 'Option a'
39 shift
40 continue
42 '-b'|'--b-long')
43 echo "Option b, argument '$2'"
44 shift 2
45 continue
47 '-c'|'--c-long')
48 # c has an optional argument. As we are in quoted mode,
49 # an empty parameter will be generated if its optional
50 # argument is not found.
51 case "$2" in
52 '')
53 echo 'Option c, no argument'
56 echo "Option c, argument '$2'"
58 esac
59 shift 2
60 continue
62 '--')
63 shift
64 break
67 echo 'Internal error!' >&2
68 exit 1
70 esac
71 done
73 echo 'Remaining arguments:'
74 for arg; do
75 echo "--> '$arg'"
76 done