Bash – How to implement dynamic bash auto completion

autocompletebashshell

I have made a script that lists available projects. You can start a project by entering script start <project>.

Now it would be great to enable autocompletion, so if you're entering start Organand press TAB, it autocompletes to start Organisation.

The difficult part is that the list of projects is dynamic. The list of available projects changes frequently and all users have different available projects.

My idea was to save the available projects into a json file and use this file to enable the autocompletion. I know that I have to create a file in /etc/bash_completion.d/, but I don't know how I can implement a "dynamic" autocompletion that depends on the available projects.

Best Answer

Let assume you have a script called output_projects that lists all available projects. Now call it from a bash function:

_list_projects() {
  ./output_projects
}

Now bind it to start like in our example with something like this:

complete -F __list_projects start

Basically, each time you press <tab> bash will execute the function and get a fresh list of available projects.

Tested on:

$ bash --version | head -1
GNU bash, version 4.3.11(1)-release (x86_64-pc-linux-gnu)

Did that solve your problem? If not please rephrase and clarify what you was looking after.