When I use program like svn
and I type in Gnome Terminal:
svn upd
and hit Tab it's autocompleted to:
svn update
Is it possible to do something like that in my custom bash script?
When I use program like svn
and I type in Gnome Terminal:
svn upd
and hit Tab it's autocompleted to:
svn update
Is it possible to do something like that in my custom bash script?
You'll have to create a new file:
For a static autocompletion (
--help
/--verbose
for instance) add this:COMP_WORDS
is an array containing all individual words in the current command line.COMP_CWORD
is an index of the word containing the current cursor position.COMPREPLY
is an array variable from which Bash reads the possible completions.And the
compgen
command returns the array of elements from--help
,--verbose
and--version
matching the current word"${cur}"
:Source
Here is a complete tutorial.
Let's have an example of script called
admin.sh
to which you would like to have autocomplete working.Note the option
shortlist
. Calling the script with this option will print out all possible options for this script.And here you have the autocomplete script:
Note that the last argument to complete is the name of the script you want to add autocompletion to. All you need to do is to add your autocomplete script to bashrc as :
or copy it to :
You can use the Programmable Completion. Have look at
/etc/bash_completion
and/etc/bash_completion.d/*
for some examples.All of the bash completions are stored in
/etc/bash_completion.d/
. So if you're building software with bash_completion it would be worthwhile to have the deb/make install drop a file with the name of the software in that directory. Here's an example bash completion script for Rsync:It would likely be worthwhile to review one of the bash completion files in there that most closely matches your program. One of the simplest examples is the
rrdtool
file.If all you want is a simple word based auto-completion (so no subcommand completion or anything), the
complete
command has a-W
option that just does the right thing.For example, I have the following lines in my
.bashrc
to autocomplete a program called jupyter:Now
jupyter <TAB> <TAB>
autocompletes for me.The docs at gnu.org are helpful.
It does seem to rely on the
IFS
variable being set correctly, but that hasn't caused any issues for me.To add filename completion and default BASH completion, use the
-o
option:To use this in zsh, add the following code before running the
complete
command in your~/.zshrc
:Just adding this here in case it helps anyone.
Examples aside, the definitive source/reference to learn more about this topic is the bash manual itself (i.e. type
man bash
in a terminal)Search for headings "Completing" and "Programmable Completion". (in the current version of the bash documentation, these appear around lines 2219 and 2332 respectively), and also the relevant bash builtin keywords referenced in those sections (e.g. compgen (line 2627), complete (line 2637), etc)