Line completion with custom commands Line completion with custom commands bash bash

Line completion with custom commands


Create a file "myprog-completion.bash" and source it in your .bashrc file. Something like this to get you started...

_myProgram(){  cur=${COMP_WORDS[COMP_CWORD]}  case "${cur}" in    d*) use="doSomething" ;;    n*) use="nowDoSomethingElse" ;;  esac  COMPREPLY=( $( compgen -W "$use" -- $cur ) )}complete -o default -o nospace -F _myProgram  myProgram


There is the module optcomplete which allows you to write the completion for bash autocompletion in your python program. This is very useful in combination with optparse. You only define your arguments once, add the following to your .bashrc

complete -F _optcomplete <program>

and all your options will be autocompleted.


As mentioned in other answers, in bash this can be done with the bash-builtin complete. Easier than writing a function (as in richq's answer) is using complete's option -W which lets you specify a list of words. In your example this would be:

complete -W "doSomething doSomethingElse nowDoSomethingDifferent" myProgram

As it is a one-liner you don't have to create a file for this, but you can just put it in your .bashrc.