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.
Related: How to create and run a Zsh script
Related: How to create and use aliases in Zsh
Related: How to create an autoload function in Zsh
Related: How to configure Zsh startup files
Related: Create a function in Bash
#!/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.
$ zsh -n notify-function.zsh
No output from zsh -n means Zsh parsed the function definitions and calls without finding a syntax error.
$ zsh notify-function.zsh backup: complete deploy: accepted usage: require_name <name> argument-check: failed
require_name || show_status "argument-check" "failed"
The right side runs only when require_name returns a nonzero status.
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.
$ rm -f notify-function.zsh