aboutsummaryrefslogtreecommitdiffhomepage
path: root/src/tools
diff options
context:
space:
mode:
authorjohannst <johannes.stoelp@gmail.com>2020-09-19 15:53:20 +0200
committerjohannst <johannes.stoelp@gmail.com>2020-09-19 15:53:20 +0200
commit4a5cd61b7c536ecf1bdb288cb6d584c190b1f6c7 (patch)
tree4fb16912a6f976e5f574dd81ace0ef36a754daf1 /src/tools
parent2c894f0c6803cf893fe1c8b10e835831499bb10b (diff)
downloadnotes-4a5cd61b7c536ecf1bdb288cb6d584c190b1f6c7.tar.gz
notes-4a5cd61b7c536ecf1bdb288cb6d584c190b1f6c7.zip
added bash getopts notes
Diffstat (limited to 'src/tools')
-rw-r--r--src/tools/bash.md37
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