I have a script myscript
which takes two arguments:
- hostname
- directory
How can I write my own zsh completion, so that whenever I do
mysript <TAB>
it completes from my hosts list (ie same as ssh
does) and when I do
mysript host1 <TAB>
it completes from directories in /home/martin/test/
?
Best Answer
Thank you for the interesting question. I would like to do the same in my scripts. The documentation is dense and not so easy to understand; I have not yet learned to work without actual options in the script. Here's my first attempt at accomplishing the goal with actual options.
First, I created a shell script named
myscript.sh
that uses options.Next, I determined where
zsh
looks for autocomplete files.I chose one of the directories,
/usr/local/share/zsh/site-functions
in my case. The filenames that are considered autocomplete files begin with an underscore _ character. I created the file,_myscript
, in the directory. The portion after#compdef
is the actual script name, above.I then executed
compinit
to pick up the new autocomplete definition provided by the_myscript
file. The result is that I can now use tab completion to specify a host after the-h
option and a directory after the-d
option while still maintaining some sanity in the parsing of options and option arguments in the script itself. The tab completion presents available options even before invokingmyscript.sh
as well as making option order irrelevant.Usage becomes something like the following.
Summary Solution
On the second attempt, I created a simple shell script,
zscript.sh
.And I created a file,
/usr/local/share/zsh/site-functions/_zscript
.I executed
compinit
.