bash completion

I was working on some functions in bash to make my life easier and realized that if I added custom completion to my functions, it will be really good. So I headed over to google and searched for what I wanted. I did get a lot of information on bash completion but not a single concrete example that could help me do what I wanted. So, with the help of man pages and some results from the Google pages, I was finally able to accomplish what I wanted. So here it is:

Google link that might help here.

What : Change to config file directory. The structure of directory looked something like this

somedirectory

| —- a

| —-| —-config

| —-b

| —-| —-config

and so on..

Solution

Create a function in the .bashrc

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
_conf()

{

local curw

local PATH="somedirectory"

COMREPLY=()

curw=${COMP_WORDS[COMP_CWORD]}

COMPREPLY=( $(cd $PATH/; compgen -W $(ls -d $curw*)) )

return 0

}

And then add the completion to .bashrc

1
complete -F _conf conf

compgen can be used with in-built functions to define completions with users, directories or with “-W” to complete with custom words.

and complete is used to define the function (_conf) to use with the command (conf).

Enhanced by Zemanta