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
Steps to create a function in Zsh:
- Add the greet function shell with a local name parameter to ~/.zshrc.
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.
- Insert the missing-name guard after the local declaration.
if [[ -z $name ]] then print -u2 -- 'usage: greet <name>' return 2 fiprint -u2 sends the usage message to standard error, and return 2 lets the caller detect invalid input.
- Place the greeting output before the closing brace.
print -r -- "Hello, $name"
The -r option prevents backslash escapes in the supplied name from being interpreted.
- Compare the completed function in ~/.zshrc with the full definition.
- ~/.zshrc
greet() { local name=${1-} if [[ -z $name ]] then print -u2 -- 'usage: greet <name>' return 2 fi print -r -- "Hello, $name" }
- Validate ~/.zshrc with Zsh for syntax errors.
$ zsh -n ~/.zshrc
No output means Zsh parsed the startup file without finding a syntax error.
- Load the updated ~/.zshrc into the current Zsh session.
$ source ~/.zshrc
- Call greet without an argument to confirm its usage error.
$ greet usage: greet <name>
- Call greet with a quoted multiword name to verify argument handling.
$ greet "Ada Lovelace" Hello, Ada Lovelace
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.