Macos – Bash Autocomplete Subdirectory for Custom Command

autocompletebashcommand linemacostab completion

I have tried for hours to get this working and feel like I've not come anywhere close.

I am trying to shorten our workflow by tab-completing directory names from the Mac OS X Terminal.

We have an internal tool, let's call it bob, that automatically runs commands on git submodules. What I'd like to do is get it to autocomplete the subdirectory names. The problem is, those subdirectories live in a static location.

   project directory
   ->public
     ->submodules
       ->a-module
       ->another-module
       ->other-module
       ->some-module

Commands are run from the top project directory like so:

bob start bugfix anothermodule

Rather than having to fully type out 'anothermodule', which is what we currently do, I'd love to get tab autocomplete to work. We use this workflow many times per day and shaving seconds off of it would be great and avoid typos.

The end goal is:

bob start bugfix an<tab>

would autocomplete to

bob start bugfix anothermodule

I've tried CDPATH but quickly realized this was not what I'm after, as this isn't following the cd command, only my custom command.

I have bash_completion installed but I am not very good at bash in general. Mentioning this though in case it can be a part of the solution!

Best Answer

This is an enhancement of Kamil’s excellent answer that strips the hyphen from the -module part of each sub-directory name.

bugfix)
    curdir=$(pwd)
    cd public/submodules/ 2>/dev/null && _filedir -d
    # Strip the hyphen from `-module` in each sub-directory name.
    for ((i=0; i<${#COMPREPLY[@]}; i++)); do
        COMPREPLY[$i]="${COMPREPLY[$i]/-module/module}"
    done
    cd "$curdir"
    ;;

There’s still scope for improving this section: you may have to type the hyphen, i.e., type a-Tab to get it to complete to amodule instead of a choice between amodule and anothermodule (the hyphen is still stripped by the completion function).

Related Question