Search code examples
zshtypeset

Strange array lookup in zsh


Looking at this example from pyenv-virtualenv:

typeset -g -a precmd_functions
if [[ -z \$precmd_functions[(r)_pyenv_virtualenv_hook] ]]; then
  precmd_functions=(_pyenv_virtualenv_hook \$precmd_functions);
fi

_pyenv_virtualenv_hook is a function that is declared earlier in the file.

I believe this code is checking to see whether _pyenv_virtualenv_hook is already injected into precmd_functions, but I don't understand the syntax.

What is the purpose of (r) in the array lookup?


Solution

  • The Zsh Guide Chapter on Substitutions explains the (r) flag:

    The (r) flag takes a pattern and substitutes the first element of the array matched.

    So the snippet does what you describe: Look if the element is in the array (i.e. the lookup returns a non-zero value). It is obfuscated further because the code you quote is assigned to a string to be evaluated, therefore the dollar signs are escaped (\$).