An Introduction to Programmable Completion in Bash

I am using the terminal a lot on Linux. For my project „pulseaudio-tcp“ (see here for more information) i wanted to have more comfortable command line completion in Bourne Again Shell („Bash“). After having typed in the command name pulseaudio-tcp, when pressing the Tabulator key, i would like to see a list of all possible arguments to that command.

In this article i demonstrate how to leverage the „Programmable Completion“ feature of Bash for such purposes. A reasonably recent version of Bash (4.2 or later) is assumed. You should have a basic understanding of control flow, variables, functions and arrays in Bash. In the article, we will make use of some advanced Bash features such as array expansion with pattern matching; these will be explained „on the go“ as required.

Preparation

If you do not have „pulseaudio-tcp“ installed and want to follow the examples below you could define a dummy function that just reports the parameters it has been called with:

pulseaudio-tcp() { echo "Arguments: $*" ; }

This will be sufficient to follow all examples in this article.

If you do have „pulseaudio-tcp“ installed and want to construct its completion logic from the ground up, you might want to reset the completion logic that comes with the installation:

complete -f -- pulseaudio-tcp

This will remove any existing completion logic, and the examples below will appear to you as described in this article.