Quick and Dirty Write Your Own Bash Autocomplete
Typing a command on the command line and hitting tab to get the rest of what you need is very nice. It is almost magical. Fortunately, it is quite easy to write your own script to handle this for any application you have, or write.
This is a quick and dirty intro into how to do this. It is meant to give you a jumping off point to write your own autocompletions not be a comprehensive tutorial
All the Code You Need.
To get started there is some code that you just need to add with out really understanding so you can get something done.
_djangoadmin()
{
local cur=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( $(compgen -W "runserver collectstatic" -- $cur) )
}
complete -F _djangoadmin django-admin.py
- First you are creating a new function called _djangoadmin to be called later.
- Line 3 is boilerplate to just add to your function.
- Line 4 is where the magic is. After the -W in the quotes is where you put your autocompleted commands.
- Line 6 is saying that when you type in django-admin.py and hit tab run the _djangoadmin fuction.
Conclusion
After seeing this I quickly realized that since it is fairly simple to get started I need to offer an autocomplete script if I ever write a CLI utility for other people to use. It is also useful for writing your own autocomplete for utilities that don’ have it.