Aliases work well for fixed command text, but a reusable shell shortcut often needs arguments, branching, or a meaningful return status. Zsh functions keep that logic in the shell and invoke it with the same command-like syntax as external programs.
An interactive Zsh session reads ~/.zshrc, so placing a small function there makes it available whenever the file is loaded. Function arguments become positional parameters, while local keeps a scratch variable from replacing a name used by the calling shell.
Successful syntax validation proves that ~/.zshrc parses but does not prove that the function handles its input. A multiword name tests the argument boundary, while a no-argument call exposes the explicit usage error and nonzero return path.
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
greet() {
local name=${1-}
}
Functions in ~/.zshrc load alongside its existing interactive settings. The ${1-} expansion supplies an empty value when no first argument exists.
if [[ -z $name ]]
then
print -u2 -- 'usage: greet <name>'
return 2
fi
print -u2 sends the usage message to standard error, and return 2 lets the caller detect invalid input.
print -r -- "Hello, $name"
The -r option prevents backslash escapes in the supplied name from being interpreted.
greet() {
local name=${1-}
if [[ -z $name ]]
then
print -u2 -- 'usage: greet <name>'
return 2
fi
print -r -- "Hello, $name"
}
$ zsh -n ~/.zshrc
No output means Zsh parsed the startup file without finding a syntax error.
$ source ~/.zshrc
$ greet usage: greet <name>
$ greet "Ada Lovelace" Hello, Ada Lovelace