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
Steps to create a function in Zsh:
- 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.
- 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.
- 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
- 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.
- 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.
- Remove the sample script after testing.
$ rm -f notify-function.zsh
Mohd Shakir Zakaria is a cloud architect with deep roots in software development and open-source advocacy. Certified in AWS, Red Hat, VMware, ITIL, and Linux, he specializes in designing and managing robust cloud and on-premises infrastructures.