lam*_*tor 2 command-line bash auto-completion
我想补充的bash的可编程完成自定义完成规范,做了以下情况:每当输入的命令是foo
,我想对于部分令牌之后做文件名/目录下完成foo
,但是相对于一个固定的目录(比方说/a/b/c
),而不是当前工作目录。
例如,假设/a/b/c
包含文件
hello goodbye cheers directory
Run Code Online (Sandbox Code Playgroud)
并/a/b/c/directory
包含文件
adieu ciao
Run Code Online (Sandbox Code Playgroud)
然后,输入foo go<TAB>
应该完成go
to goodbye
,并且输入foo dir<TAB>ci<TAB>
应该首先完成参数 todirectory/
然后 to directory/ciao
,无论我当前的工作目录是什么。
我希望能够通过一次调用来设置它complete
,但是在阅读手册后,我似乎无法做到这一点。可以做到吗?而且,如果没有,我怎么能添加一个 compspec 来做到这一点?
您可以使用自定义完成功能,如下所示:
_foo () {
local cur
COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
k=0
i="/a/b/c" # the directory from where to start
for j in $( compgen -f "$i/$cur" ); do # loop trough the possible completions
[ -d "$j" ] && j="${j}/" || j="${j} " # if its a dir add a shlash, else a space
COMPREPLY[k++]=${j#$i/} # remove the directory prefix from the array
done
return 0
}
Run Code Online (Sandbox Code Playgroud)
然后注册要与您的命令一起使用的函数foo
:
complete -o nospace -F _foo foo
Run Code Online (Sandbox Code Playgroud)