]> git.ipfire.org Git - thirdparty/util-linux.git/blob - misc-utils/getopt-parse.bash
libfdisk: fix fdisk_script_get_table()
[thirdparty/util-linux.git] / misc-utils / getopt-parse.bash
1 #!/bin/bash
2
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.
7
8 # Example input and output (from the bash prompt):
9 #
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!*\?'
19
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 'a-long,b-long:,c-long::' -n 'example.bash' -- "$@")
24
25 if [ $? -ne 0 ]; then
26 echo 'Terminating...' >&2
27 exit 1
28 fi
29
30 # Note the quotes around "$TEMP": they are essential!
31 eval set -- "$TEMP"
32 unset TEMP
33
34 while true; do
35 case "$1" in
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')
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
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 ;;
69 esac
70 done
71
72 echo 'Remaining arguments:'
73 for arg; do
74 echo "--> '$arg'"
75 done