Search code examples
bashbash-completion

How to define completion for function name "pattern"?


I have several functions working only with directories, all function names following this pattern (ending in _dir):

something_dir () { ... }
something_else_dir() { ... }
...

And for all of those, I define completion with:

complete -A directory something_dir something_else_dir ...

Is it possible to define completion for all functions automatically so that every new function ending in _dir would complete just directories?


Solution

  • Use compgen -A function to list all functions; then grep -E '.*_dir$' to filter out functions ending with _dir.

    complete -A directory $(compgen -A function | grep -E '.*dir$')
    

    This assumes that all function names ending with _dir are free of special symbols like * and spaces. According to the specification, this should always be the case.

    This command will only set up completion for already existing functions. To automatically add completion for functions you will define in an interactive session, add the command to PROMPT_COMMAND so that it will be executed at every prompt.

    PROMPT_COMMAND="complete -A directory \$(compgen -A function | grep -E '.*dir$')"