An Introduction to Programmable Completion in Bash

Parameter Completion Logic

If no specific completion logic is associated with a command at all, Bash falls back to the default behavior of offering the filenames in the current working directory as possible completions. To test this, just press Tabulator to complete the first parameter to pulseaudio-tcp, and you will see a list of files in your current directory. This is undesirable; it would suggest to the user that the command can be invoked with names of files as parameters, which is not supported and would lead to an error.

Bash offers two ways of defining parameter completion logic for commands:

  1. Variant 1: Provide a static list of words that are valid parameters.
  2. Variant 2: Provide the name of a Bash function that interprets the current contents of the command line and determines possible completions in a context-sensitive manner.

In Bash, there are two built-in commands that are important for defining completion logic:

  • complete: Associates completion logic such as word lists or functions with command names.
  • compgen: Compares a given incomplete word with a word list and emits a list of possible completions.

Their usage will be demonstrated in the next section.