functions 

Send to Kindle
home » snippets » zsh » functions



Autoloading functions

Ref: http://unix.stackexchange.com/a/33898

# This marks myfunc to be loaded when used by searching $fpath (not recursively.)
# -U: suppress alias expansion during function load
# -z: use zsh style function definition/loading instead of ksh style.
autoload -Uz myfunc

Now, when you type myfunc, it will find a file named myfunc under $fpath and run that to load the function.

Defining functions under $fpath

The contents of the file myfunc under $fpath used to define the function myfunc can be written in one of 3 ways using the ZSH scheme (NOT the ksh scheme.)

1. File contains the body of the function

e.g. contents of myfunc

print Running myfunc

2. File contains the full definition of the function

e.g. contents of myfunc

myfunc() {
  print Running myfunc
}

2. File contains multiple function definitions

You can have multiple function definitions in the file. You must define one function with the same name as the file that defines the function being loaded. In addition, you must call the primary function at the end of the file and pass it arguments. Note that the extra function will be visible in the global scope from this point onwards (and redefine or shadow existing names.)

e.g. contents of myfunc

foo() {
  print foo
}

bar() {
  print bar
}

myfunc() {
  print Running myfunc
}

myfunc "$@"