Autoload functions let Zsh expose custom helper commands without reading every function body during shell startup. They fit personal commands that live in separate files but should still be available when an interactive Zsh session starts.
Zsh finds autoload files through the fpath array, not the executable PATH. Each file normally uses the same name as the function registered with autoload -Uz, and the first call loads the file before running the function.
A small say_project function stored under ~/.zsh/functions keeps the example limited to one user-owned function file. Fresh zsh -ic checks first show the unresolved autoload marker, then prove the file ran by printing the supplied argument.
Related: How to create a function in Zsh
Related: How to configure Zsh startup files
Related: How to manage PATH with the Zsh path array
$ mkdir -p ~/.zsh/functions
say_project() {
emulate -L zsh
print -r -- "project=${1:-demo}"
}
The file name and function name should match when using normal Zsh autoload behavior. emulate -L zsh gives the function native Zsh option behavior while it runs.
fpath=("$HOME/.zsh/functions" $fpath)
autoload -Uz say_project
Put the personal function directory before the existing fpath entries so Zsh finds the personal definition first.
$ zsh -n ~/.zsh/functions/say_project
No output from zsh -n means Zsh parsed the function file without finding a syntax error.
$ zsh -n ~/.zshrc
No output from zsh -n means Zsh parsed the startup file without finding a syntax error.
$ zsh -ic 'functions say_project'
say_project () {
# undefined
builtin autoload -XUz
}
$ zsh -ic 'say_project alpha' project=alpha
Use autoload -Uz for shell functions so aliases are not expanded while the function file is loaded.