40

I have my custom console utility cooltool with list of options

fooOption
barOption

What should I do to able bash autocomplete the options by pressing the tab key?

I mean the user typed

$ ./cooltool foo_

then pressed tab. And then

$ ./cooltool fooOption _

appeared.

2
  • 1
    Don't cross post.
    – Wuffers
    May 27, 2011 at 18:41
  • 2
    Notice that this one is migrated and the other isn't. I think a lot of users still don't realize that they shouldn't be posting a question on multiple SE sites. They're used to disparate forums that aren't a unified system, where you might ask in a few different forums for a better chance of a fast answer. May 27, 2011 at 18:43

5 Answers 5

4

Write a bash completion script for cooltool. The bash-completion package comes with scripts for many popular programs, which you can use as examples.

0
51

The simplest way is to add the following to your .bashrc.

_cooltool()
{
    local cur=${COMP_WORDS[COMP_CWORD]}
    COMPREPLY=( $(compgen -W "fooOption barOption" -- $cur) )
}
complete -F _cooltool cooltool

Whenever you type cooltool f[TAB][TAB], the _cooltool() function is invoked. It will work out what your current partial word is and then compgen will work out which options match. These are stored in an array called COMPREPLY which is then displayed. Look at man complete and man compgen for details.

For a nice tutorial check out: Writing your own Bash Completion Function

8

You might want to take a closer look inside your /etc/bash_completion.d directory on your system.

Also you should read this introduction. The second part of the introduction is the one you need.

2
  • 1
    I am using the Mac OS X 10.6, so there is no /etc/bash_completion.d directory
    – user83293
    May 27, 2011 at 17:03
  • Ah Ok, good to know.
    – Anonymous
    May 27, 2011 at 17:06
3

Here is the code that is used for git bash completion

2
  • interesting to read :)
    – user83293
    May 27, 2011 at 17:02
  • 10
    Please include at least a summary of the answer in your answer, not just a link. See the site FAQ.
    – Caleb
    May 28, 2011 at 8:08
3

In addition to dogbane's answer, you could also do:

complete -W "fooOption barOption" cooltool

if you simply want to match a list of words from the beginning of the string. It seems that complete and compgen share most options. I've only noticed "beginning of string" matching in the commands I use, so I found it neat that you can do other things in the _cooltool function like:

COMPREPLY=( $(grep "$cur" ~/my_potential_args.txt) )

to match anywhere in the option name.

You must log in to answer this question.