2

I have written bash-completion for a command line utility. I need to support zsh.
What is the best/standard way to maintain completion for bash and zsh?

I could write separate zsh-completion but I don't want to maintain separate completion for each shell.

I could use bash-completion in zsh (like this) but I don't want to force my users to manually set up the tool or to modify their ~/.zshrc during installation.

Other people will install this utility using Homebrew/Linuxbrew. I can modify the installation Formula.

curusarn
  • 403
  • 4
  • 11

1 Answers1

1

Following code can be used as completion for both bash and zsh.
This is working but not an ideal solution. Use with care.

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
curusarn
  • 403
  • 4
  • 11