bash completion

2011-08-09 293 words 2 mins read

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

  <td>
    <div class="text codecolorer">
      _conf()<br /> <br /> {<br /> <br /> local curw<br /> <br /> local PATH="somedirectory"<br /> <br /> COMREPLY=()<br /> <br /> curw=${COMP_WORDS[COMP_CWORD]}<br /> <br /> COMPREPLY=( $(cd $PATH/; compgen -W $(ls -d $curw*)) )<br /> <br /> return 0<br /> <br /> }
    </div>
  </td>
</tr>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

And then add the completion to .bashrc

  <td>
    <div class="text codecolorer">
      complete -F _conf conf
    </div>
  </td>
</tr>
1

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

author

Authored By Amit Agarwal

Amit Agarwal, Linux and Photography are my hobbies.Creative Commons Attribution 4.0 International License.

We notice you're using an adblocker. If you like our webite please keep us running by whitelisting this site in your ad blocker. We’re serving quality, related ads only. Thank you!

I've whitelisted your website.

Not now
This website uses cookies to ensure you get the best experience on our website. Learn more Got it