Search code examples
shellcommand-linezshflagszshrc

Can zsh complete command flags?


Is there some way to get zsh to complete long flag names on the command line?

$ command --reall<tab> 
$ command --really-long-flag-name

Seems like a zshy thing to do.


Solution

  • The short answer is yes, or course it can.

    To turn on zsh’s completion system, you need to do the following – probably in a startup file like your ~/.zshrc:

    autoload -U compinit && compinit
    

    On most modern Unix-like systems, once you do that you ought to find that many commands already have their flags and parameters completed, because zsh ships with a library of completion functions for common Unix commands and utilities. This library ought to be installed in a location like /usr/local/share/zsh/function (or similar, depending on your system) and consists of a bunch of scripts with filenames starting in a _ character, each of which defines the completion for a specific command.

    If a command or utility you’re interested in is not yet completed correctly by zsh, you have several options:

    • Look into the zsh-completions package. (It may well be installable by your operating system or distribution’s package manager.)

    • Read the documentation for the tool you wish to have completion. Many Unix utilities ship with completion scripts for bash and/or zsh, or with some way of generating completion scripts.

    • If all else fails, read the documentation on zsh’s completion system (or find a good book or online tutorial) and write it yourself. This can — obviously — be non-trivial!

    Reading that zsh documentation might also show you how to do other things that you may not even know yet that you want, like turning on menu-based completion.