From 4a5cd61b7c536ecf1bdb288cb6d584c190b1f6c7 Mon Sep 17 00:00:00 2001 From: johannst Date: Sat, 19 Sep 2020 15:53:20 +0200 Subject: added bash getopts notes --- src/tools/bash.md | 37 ++++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) (limited to 'src') 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 [] +``` +- `` specifies the names of supported options, eg `f:c` + - `f:` means `-f` option with an argument + - `c` means `-c` option without an argument +- `` specifies a variable name which `getopts` fills with the last parsed option argument +- `` 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