Variant 1: Using a Word List
In our example, we could interpret the union of all options and all command verbs as the set of words that may follow the command name. By that definition, the following is a list of words that may follow the command name pulseaudio-tcp:
- --help
- --debug
- --nogui
- start
- stop
- restart
- status
- setup
Bash can be instructed to associate this word list using the built-in function complete which takes a space-separated list of all these words as a single argument to it’s -W option:
complete -W "--help --debug --nogui start stop restart status setup" -- pulseaudio-tcp
Now, if you type the Tabulator key after the first complete word, you will be informed about the possible completions of the second word:
prompt> pulseaudio-tcp␣␉
--debug --help --nogui restart setup start status stop
If you start typing a prefix of one or more of the available completions, narrowing down the set of possible completions that can continue, and then press Tabulator again, a reduced set of choices will be displayed. For example, if you type -- and then press Tabulator, only the three „options“ of pulseaudio-tcp (--debug, --help and --nogui) will be shown as possible word completions:
prompt> pulseaudio-tcp␣--␉
--debug --help --nogui
You can use the built-in command compgen to simulate the set of possible completions the command line interpreter would provide if given some incomplete word, for example the string st:
prompt> compgen -W "--help --debug --nogui start stop restart status setup" -- st
start
stop
status
Congratulations! You have defined a Bash command line completion, and terminal users can now easily inform themselves about all valid arguments that the command supports.
- Bourne to Bourne Again Shell Forward Compatibility
- Print XDG Desktop Definition for Application
- Using sed or awk to ensure a specific last Line in a Text
- Make a Bourne Again Shell Script Log its Output to a File
- Maintaining Multi-Line „stat“ Formats using Bourne Again Shell
- Print all indented Lines following a non-indented Line
- An Introduction to Programmable Completion in Bash