我有一个shell脚本,它的使用方法如下:
foo.sh <name> <type> <*.tar.gz>
我希望只使用第三个参数来设置完整内容。如果我按下第一个参数,只显示用法。
我能否使用zsh的zshcomp来完成这项工作?
例如:
foo.sh <tab> # display usage
foo.sh a b <tab> # show files match with *.tar.gz
有没有类似的脚本可以供我参考?
foo.sh <name> <type> <*.tar.gz>
我希望只使用第三个参数来设置完整内容。如果我按下第一个参数,只显示用法。
我能否使用zsh的zshcomp来完成这项工作?
例如:
foo.sh <tab> # display usage
foo.sh a b <tab> # show files match with *.tar.gz
这篇博客文章讨论了Z-Shell Completion System。
如果您想要更深入的讨论,请阅读这个unix.stackexchange的回答。
同时,阅读man pages!
编辑:忘记补充了:echo $fpath
会显示zsh
使用的函数路径。在OSX上,我有:/usr/local/share/zsh/4.3.17/functions
(可能因人而异),其中包含所有的ZSH完成函数。查看一下_ssh
、_ls
、_tar
等文件——它们都在那里,并且它们都有很多巧妙的功能可以学习。
虽然需要几个步骤,但你所问的是可以实现的。
You need to write a z-shell completion function. It needs to be located on the fpath
; the function-path that zsh
uses for it's completion system functions. (If it's a small function, putting it into ~/.zshrc
will also work, but isn't recommended).
You want completion on the 3rd parameter. To do that, your function would look something like the following:
_arguments "3:<MENU>:<COMPLETION>"
<MENU>
is the menu description, which you'll see if you've enabled the menu descriptions. (That's done using zstyle
; read the man pages, or the linked pages, for more information).
<COMPLETION>
is the things that you can complete with. For example, if you used:
_arguments "3::(Foo Bar)"
when you ran your script and pressed <TAB>
, you'd have the option of either Foo
or Bar
.
[NOTE: There is no <MENU>
in that example. If you don't want a menu descriptor, you can omit it as shown].
You want completion on *.tar
files. You can call _files
to do that:
_files -g \*.tar
Show usage on first parameter: that'd be a completion with no arguments (ie, argument 1). I'm not sure why you'd want completion on only the third option but not the first two (typical usage descriptions), so I don't know how to answer this. If your script is supposed to be used like this: script foo bar FILE.tar
, wouldn't you want to complete the foo
and bar
arguments as well?
Perhaps a better solution would be displaying the usage when the script is run without parameters.
完整的脚本应该如下所示:
#compdef myscript
_arguments "3:tar files:_files -g \*.tar"
_arguments "3::(Foo Bar)"
不起作用。应该在冒号之间有空格,即_arguments "3: :(Foo Bar)"
。 - Aleksey