An Introduction to Programmable Completion in Bash

Shortcomings of a Word List

The simple word list approach shown above has a few shortcomings:

  1. Given a word list alone, the command line interpreter can not react to more complex requirements, for example:
    • The command could have a complex synopsis with certain command verbs having specific options, i.e. like this: COMMAND VERB1 [VERB1_OPTION …] VERB2 [VERB2_OPTION …].
    • The command could feature options that consume one or more the following parameter as their value argument, e.g. like this: COMMAND [--mode {mode1|mode2}].
    • It could even be a requirement to support options that take arguments in two different writings: --option=ARGUMENT and --option ARGUMENT.

    Luckily, the example command pulseaudio-tcp does not have such elaborate requirements.

  2. However, what might come to our attention is the following: Bash’s completion now offers completion of infinitely many parameters; no matter how many options and command verbs are already present, the user can just Tab-complete on and on, generating more and more parameters to pulseaudio-tcp. Such invocations might not even be supported and could lead to errors; for example, if you have already typed in the command verb stop, it is not correct to type in any more command verbs, but Bash will show them as possible completions anyway:
prompt> pulseaudio-tcp␣stop␣s
setup start status stop 

This is not desirable; the user could assume that a command line such as pulseaudio-tcp stop start was valid, which it is not.

The function-based completion logic as shown in the following sections can take into account the current contents of the command line and determine a set of possible completions depending on what already has been typed in.