diff options
Diffstat (limited to 'src/tools')
-rw-r--r-- | src/tools/bash.md | 37 |
1 files changed, 36 insertions, 1 deletions
diff --git a/src/tools/bash.md b/src/tools/bash.md index a4df7da..3f53045 100644 --- a/src/tools/bash.md +++ b/src/tools/bash.md @@ -98,6 +98,41 @@ command 2>&1 >file 1. duplicate `fd 1` to `fd 2`, effectively redirecting `stderr` to `stdout` 2. redirect `stdout` to `file` +## Argument parsing with `getopts` + +The `getopts` builtin uses following global variables: +- `OPTARG`, value of last option argument +- `OPTIND`, index of the next argument to process (user must reset) +- `OPTERR`, display errors if set to `1` + +```bash +getopts <optstring> <param> [<args>] +``` +- `<optstring>` specifies the names of supported options, eg `f:c` + - `f:` means `-f` option with an argument + - `c` means `-c` option without an argument +- `<param>` specifies a variable name which `getopts` fills with the last parsed option argument +- `<args>` optionally specify argument string to parse, by default `getopts` parses `$@` + +### Example +```bash +#!/bin/bash +function parse_args() { + while getopts "f:c" PARAM; do + case $PARAM in + f) echo "GOT -f $OPTARG";; + c) echo "GOT -c";; + *) echo "ERR: print usage"; exit 1;; + esac + done + # users responsibility to reset OPTIND + OPTIND=0 +} + +parse_args -f xxx -c +parse_args -f yyy +``` + ## Completion The `complete` builtin is used to interact with the completion system. @@ -124,7 +159,7 @@ COMPREPLY # array with possible completions The `compgen` builtin is used to generate possible matches by comparing `word` against words generated by `option`. ```bash -compgen [option] [word] +compgen <option> <word> # usefule options: # -W <list> specify list of possible completions |