使用命令的输出为 zsh 生成自动完成命令

Maj*_*aby 5 shell zsh autocomplete

嘿,我正在尝试让 zsh 运行 git 命令,并使用输出生成自动完成的可能性。

我试图运行的命令是

git log -n 2 --pretty=format:"'%h %an'"
Run Code Online (Sandbox Code Playgroud)

这是我正在使用的代码:

local lines words

lines=(${(f)$(git log -n 2 --pretty=format:"'%h %an'")})
words=${(f)$(_call_program foobar git log -n 2 --pretty=format:"%h")}

echo "Length of lines is " ${#lines[@]} " value is " ${lines}
echo "Length of words is " ${#words[@]} " value is " ${words}

compadd -d lines -a -- words
Run Code Online (Sandbox Code Playgroud)

这根本不起作用......它认为这words是一个单一的元素并且线条根本没有正确打印。

但是,当我尝试手动设置字符串数组时,一切正常。

local lines words

lines=('one two' 'three')
words=('one two' 'three')

echo "Length of lines is " ${#lines[@]} " value is " ${lines}
echo "Length of words is " ${#words[@]} " value is " ${words}

compadd -d lines -a -- words
Run Code Online (Sandbox Code Playgroud)

ZyX*_*ZyX 4

要强制单词成为数组,您应该使用

words=( ${(f)...} )
Run Code Online (Sandbox Code Playgroud)

或者

set -A words ${(f)...}
Run Code Online (Sandbox Code Playgroud)

。如果您只使用words=${(f)...},您将始终得到一个值。顺便问一下,为什么你${(f)...}在编写定义时添加了括号lines,但没有这样做words

另外,还有一件事需要关注:${(f)$(...)}应该替换为${(f)"$(...)"}. 这里有一些黑魔法:我不知道为什么第一个确实发出单个标量值,而第二个确实发出标量值数组,只是有人在 stackoverflow 上指出了这一事实。