Taking advantage of the Programmable Tab Completion in Bash, Bash scripts that have subcommands can provide TAB completion in order to discover these subcommands in the following manner:
-
Gather a list of subcommands dynamically, say in a list
COMMANDS
-
Use the following code to give completion output
if [[ -n $COMP_LINE ]]; then line=${COMP_LINE#* } for c in "${COMMANDS[@]}"; do [[ ${c:0:${#line}} == "${line,,}" ]] && echo "$c" done exit fi
Explaination:
- Check to see if we are in Tab completion mode. Presence of
COMP_LINE
is an indication or this. - Get the current word we are typing.
- Match the incomplete work with names of commands in
COMMANDS
- echo any sub-commands that match
- Check to see if we are in Tab completion mode. Presence of
-
Add
complete -C prog prog
to~/.bashrc
, whereprog
is the program that the above completion code would be a part of.
Related:
- 20220113084600 Programmable Tab Completion in Bash
- 20220114044631 Bash Construct List of Sub-Commands
Reference:
man bash
- @rwxrob's Bash Command Template: https://github.com/rwxrob/template-bash-command
Tags:
#literature-note #scripting #tips