A Zsh function gives a reusable shell action a name, so a script or interactive startup file can call the same logic with different arguments. It fits shortcuts that need parameters, validation, return statuses, or more than one command, which makes it the next step after simple aliases.

Function arguments use the function's own positional parameters such as $1 and $2. Variables declared with local stay inside the function, print -r writes text without interpreting backslash escapes, and print -u2 sends usage text to standard error.

The sample script defines one status helper and one argument check. Syntax validation with zsh -n catches parse errors before running the file, and the run output shows the normal branch, the failed argument check, and the caller's response to the nonzero return status.

Steps to create a function in Zsh:

  1. Create a Zsh script with named functions.
    notify-function.zsh
    #!/usr/bin/env zsh
    set -e
     
    show_status() {
        local name=$1
        local state=${2:-ready}
        print -r -- "$name: $state"
    }
     
    require_name() {
        if (( $# == 0 )); then
            print -r -u2 -- "usage: require_name <name>"
            return 1
        fi
     
        show_status "$1" "accepted"
    }
     
    show_status "backup" "complete"
    require_name "deploy"
    require_name || show_status "argument-check" "failed"

    Function arguments are separate from the script's arguments. Inside require_name, $1 means the first argument passed to that function call.

  2. Check the script syntax.
    $ zsh -n notify-function.zsh

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

  3. Run the script and confirm that both function branches execute.
    $ zsh notify-function.zsh
    backup: complete
    deploy: accepted
    usage: require_name <name>
    argument-check: failed
  4. Use a return status when the caller needs to react to a failed function check.
    require_name || show_status "argument-check" "failed"

    The right side runs only when require_name returns a nonzero status.

  5. Keep temporary function variables local.
    local name=$1
    local state=${2:-ready}

    local prevents helper values inside a function from overwriting variables used by the rest of the script or interactive shell.

  6. Remove the sample script after testing.
    $ rm -f notify-function.zsh