diff options
-rw-r--r-- | src/bash.md | 40 |
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 |