7

I shifted to zsh from bash recently.

When I run complete -f _ssh sshrc it's showing

zsh: command not found: complete
  • What is the alternative to bash complete in zsh?

  • How to add an alias command to auto completions in zsh shell?

Kusalananda
  • 333,661
Akhil
  • 1,290

1 Answers1

6

I assume you're using the “new completion system” (compinit), if not see below.

By default, zsh expands aliases before performing completion, so if sshrc is an alias for ssh with some extra options, you'll get completion out of the box. But if sshrc is a function or script, you need to explain how to complete it.

To make a command use a specific function, use the compdef function:

compdef _ssh sshrc

There's an additional difficulty with _ssh which you won't run into with most completion functions: it acts differently based on the command name, or more precisely based on the “service name” which by default is the command name. If _ssh doesn't recognize the command name, it doesn't offer any completions.

To make sshrc be completed like ssh, instruct zsh to do this directly. This not only sets up sshrc to be completed with the _ssh function, but also declares the service name for sshrc to be ssh so that _ssh works properly.

compdef sshrc=ssh

Under the hood, this performs

_comps[sshrc]=$_comps[ssh]
_services[sshrc]=ssh

Completion systems in zsh

Zsh has three completion mechanisms: “old-style” completion with compctl, “new-style” completion (which was introduced in the 1990s, so it's not exactly newfangled), and a compatibility layer for bash completion.

By default, zsh uses the old completion system, for backward compatibility. But anyone who started using zsh after the new completion system became available should use that. The new user wizard offers to add the requisite lines to your configuration file. If you didn't get a chance to run it, or you want to re-run it, see Run the Zsh first use wizard, select “Use the new completion system.”, tune settings as desired, and confirm the changes until they're saved.

If you put bashcompinit in your .zshrc, it defines a complete function that's mostly compatible with bash. The compatibility is not perfect, but it's good enough to run most of the completion functions that people write and distribute with their own programs.

P.S. As a new user of zsh, you may be interested in my overview of the differences between bash and zsh.

  • compdef _ssh sshrc not working at all. but compdef _telnet sshrc is working.something weird is happening between ssh and sshrc script file. – Akhil Jun 18 '20 at 12:05
  • 1
    @AkhilJ Indeed. See my edited answer. You need compdef sshrc=ssh. What I showed was the old-fashioned way which isn't enough, but these days there's a better way. – Gilles 'SO- stop being evil' Jul 25 '20 at 20:06
  • Thanks for the update. It worked. @Gilles 'I am not evil'. – Akhil Jul 27 '20 at 06:33