I have my custom console utility cooltool with list of options


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 _


  • 1
    Don't cross post. – Wuffers May 27 '11 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. – jcrawfordor May 27 '11 at 18:43

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

| improve this answer | |

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

    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

| improve this answer | |

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.

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

Here is the code that is used for git bash completion

| improve this answer | |
  • interesting to read :) – user83293 May 27 '11 at 17:02
  • 8
    Please include at least a summary of the answer in your answer, not just a link. See the site FAQ. – Caleb May 28 '11 at 8:08

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.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy