]> git.ipfire.org Git - thirdparty/util-linux.git/blame - misc-utils/getopt-parse.bash
lscpu: add --bytes
[thirdparty/util-linux.git] / misc-utils / getopt-parse.bash
CommitLineData
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
6# as getopt-parse.tcsh.
2b6fc908
KZ
7
8# Example input and output (from the bash prompt):
d27f5fe7
SK
9#
10# ./getopt-parse.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 23TEMP=$(getopt -o 'ab:c::' --long 'a-long,b-long:,c-long::' -n 'example.bash' -- "$@")
2b6fc908 24
d27f5fe7
SK
25if [ $? -ne 0 ]; then
26 echo 'Terminating...' >&2
27 exit 1
28fi
2b6fc908 29
d27f5fe7 30# Note the quotes around "$TEMP": they are essential!
2b6fc908 31eval set -- "$TEMP"
d27f5fe7 32unset TEMP
2b6fc908 33
d27f5fe7 34while 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
70done
d27f5fe7
SK
71
72echo 'Remaining arguments:'
73for arg; do
74 echo "--> '$arg'"
75done