Programmable Completion (Bash Only)

Bash and the readline library provide completion facilities, whereby you can type part of a command name, hit the TAB key, and have Bash fill in part or all of the rest of the command or filename. Programmable completion lets you, as a shell programmer, write code to customize the list of possible completions that Bash will present for a particular, partially entered word. This is accomplished through the combination of several facilities.

  • The complete command allows you provide a completion specification, or compspec, for individual commands. You specify, via various options, how to tailor the list of possible completions for the particular command. This is simple, but adequate for many needs. (See the complete entry in the section "Built-in Commands (Bash and Korn Shells),” later in this chapter.)

  • For more flexibility, you may use complete -F funcname command. This tells Bash to call funcname to provide the list of completions for command. You write the funcname function.

  • Within the code for a -F function, the COMP* shell variables provide information about the current command line. COMPREPLY is an array into which the function places the final list of completion results.

  • Also within the code for a -F function, you may use the compgen command to generate a list of results, such as “usernames that begin with a" or “all set variables.” The intent is that such results would be used with an array assignment:

    ...
    COMPREPLY=( $( compgen options arguments ...

Get Unix in a Nutshell, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.