Programmable Completion

Bash and the readline library provide completion facilities, whereby you can type part of a command name, press 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 in Built-in Commands.)

  • 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 is 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 ) )

Compspecs may be associated ...

Get Linux in a Nutshell, 6th 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.