How to create an autoload function in Zsh

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.

Steps to create an autoload function in Zsh:

  1. Create a directory for personal Zsh functions.
    $ mkdir -p ~/.zsh/functions
  2. Create one function file named after the function.
    ~/.zsh/functions/say_project
    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.

  3. Add the function directory and autoload command to ~/.zshrc.
    ~/.zshrc
    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.

  4. Check the function file for syntax errors.
    $ zsh -n ~/.zsh/functions/say_project

    No output from zsh -n means Zsh parsed the function file without finding a syntax error.

  5. Check the startup file for syntax errors.
    $ zsh -n ~/.zshrc

    No output from zsh -n means Zsh parsed the startup file without finding a syntax error.

  6. Start a new interactive Zsh shell and confirm the function is marked for autoloading.
    $ zsh -ic 'functions say_project'
    say_project () {
    	# undefined
    	builtin autoload -XUz
    }
  7. Run the function and confirm that the autoloaded file executed.
    $ zsh -ic 'say_project alpha'
    project=alpha

    Use autoload -Uz for shell functions so aliases are not expanded while the function file is loaded.