aboutsummaryrefslogtreecommitdiffhomepage
diff options
context:
space:
mode:
authorjohannst <johannes.stoelp@gmail.com>2020-04-12 16:55:54 +0200
committerjohannst <johannes.stoelp@gmail.com>2020-04-12 16:55:54 +0200
commit577e88c0ac47fb48faf151afbead333dfe752909 (patch)
tree1331636cdb5ff3a3f7709d5d5a86929fcef40fd2
parentf81b1f23a526450e16992e2e248495365d9e394d (diff)
downloadnotes-577e88c0ac47fb48faf151afbead333dfe752909.tar.gz
notes-577e88c0ac47fb48faf151afbead333dfe752909.zip
updated bash, added completion example
-rw-r--r--src/bash.md40
1 files changed, 35 insertions, 5 deletions
diff --git a/src/bash.md b/src/bash.md
index 1dd35a8..a4df7da 100644
--- a/src/bash.md
+++ b/src/bash.md
@@ -121,19 +121,49 @@ COMP_CWORD # index into COMP_WORDS with current cursor position
COMPREPLY # array with possible completions
```
-`compgen` builtin is used to generate possible matches for `word` out of possible `option`s.
-The syntax is as follows:
+The `compgen` builtin is used to generate possible matches by comparing `word`
+against words generated by `option`.
```bash
compgen [option] [word]
# usefule options:
+# -W <list> specify list of possible completions
+# -d generate list with dirs
+# -f generate list with files
+# -u generate list with users
+# -e generate list with exported variables
-# -W <list> compare against word-list
+# compare "f" against words "foo" "foobar" "bar" and generate matches
compgen -W "foo foobar bar" "f"
-# -d compare against dir names
-# -f compare against file names
+# compare "hom" against file/dir names and generate matches
compgen -d -f "hom"
```
+### Example
+Skeleton to copy/paste for writing simple completions.
+
+Assume a program `foo` with the following interface:
+```bash
+foo -c green|red|blue -s low|high -f <file> -h
+```
+
+The completion handler could be implemented as follows:
+```bash
+function _foo() {
+ local curr=$2
+ local prev=$3
+
+ local opts="-c -s -f -h"
+ case $prev in
+ -c) COMPREPLY=( $(compgen -W "green red blue" -- $curr) );;
+ -s) COMPREPLY=( $(compgen -W "low high" -- $curr) );;
+ -f) COMPREPLY=( $(compgen -f -- $curr) );;
+ *) COMPREPLY=( $(compgen -W "$opts" -- $curr) );;
+ esac
+}
+
+complete -F _foo foo
+```
+
[dup2]: http://man7.org/linux/man-pages/man2/dup.2.html