How to create a function in Zsh

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.

Steps to create a function in Zsh:

  1. 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.

  2. Insert the missing-name guard after the local declaration.
    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.

  3. 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.

  4. 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"
    }
  5. Validate ~/.zshrc with Zsh for syntax errors.
    $ zsh -n ~/.zshrc

    No output means Zsh parsed the startup file without finding a syntax error.

  6. Load the updated ~/.zshrc into the current Zsh session.
    $ source ~/.zshrc
  7. Call greet without an argument to confirm its usage error.
    $ greet
    usage: greet <name>
  8. Call greet with a quoted multiword name to verify argument handling.
    $ greet "Ada Lovelace"
    Hello, Ada Lovelace