Search code examples
linuxbashautocompletekeystroke

find based filename autocomplete in Bash script


There is a command line feature I've been wanting for a long time, and I've thought about how to best realize it, but I got nothing...

So what I'd like to have is when I start typing a filename and hit tab,for example:

# git add Foo<tab>

I'd like it to run a find . -name "*$1*" and basically autocomplete the complete path to the matched File to my command line.

What I have so far:

I know I'll have to write a function that will call the app with the parameters I want, for example git add. After that it needs to catch the tab-keystroke event and do the find mentioned above, and display the results if many, or fill in the result if one.

What I haven't been able to figure out:

How to catch the tab key event within a function within function.

So basically in pseudocode:

gadd() {git add autocomplete_file_search($1)}

autocomplete_file_search(keyword) {
  if( tab-key-pressed ){
    files = find . -name "*$1*";
    if( filecount > 1 ) {
      show list;
    }
    if( files == 1 ) {
      return files
    }
  }
}

Any ideas?

thanks.


Solution

  • You should take a look at this introduction to bash completion. Briefly, bash has a system for configuring and extending tab completion. Other shells do this, too, and each one has a different way to set it up. Using this system it is not necessary to do everything yourself and adding custom argument completion to a command is relatively easy.