为bash和zsh开发和维护shell完成

时间:2018-02-07 23:51:22

标签: bash zsh maintainability tab-completion

我为命令行实用程序编写了bash-completion。 我需要支持zsh。
保持bash和zsh完成的最佳/标准方法是什么?

我可以编写单独的zsh-completion但是我不想为每个shell维护单独的完成。

我可以在zsh(like this)中使用bash-completion,但我不想强迫我的用户在安装过程中手动设置工具或修改他们的~/.zshrc

其他人将使用Homebrew / Linuxbrew安装此实用程序。我可以修改安装公式。

1 个答案:

答案 0 :(得分:0)

以下代码可用作bash和zsh的完成。
这是有效但不是理想的解决方案。小心使用。

if [ ! -z "$ZSH_NAME" ]; then 
    # zsh sets $ZSH_NAME variable so it can be used to detect zsh
    # following enables using bash-completion under zsh
    autoload bashcompinit
    bashcompinit
fi

_example() {
    # arbitrary bash-completion function
    local cur prev

    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    if [[ ${prev} == example ]] ; then
        COMPREPLY=( $(compgen -W "--help --something" -- ${cur}) )
    else
        COMPREPLY=()
    fi
    return 0
}  
# you can use complete builtin in both bash and zsh now
complete -F _example example