Large Zsh startup files, sourced helpers, and autoload libraries can slow repeated shell launches when every process parses the same source text. Compiling a script into a .zwc wordcode file gives Zsh a parsed cache to load later while the plain source stays as the file people edit.
The zcompile builtin reads a Zsh source file and writes the compiled file next to it by default. Zsh uses matching wordcode for source and autoload lookups when the .zwc file is newer than the source, so rebuild the compiled file after changing the script.
A small sourceable script keeps verification direct by checking syntax, running the source, compiling it, and inspecting the generated wordcode with zcompile -t. A .zwc file is tied to Zsh wordcode rather than a portable executable format, so keep the original script available.
Related: How to create an autoload function in Zsh
Related: How to configure Zsh startup files
Steps to compile a Zsh script:
- Create a sourceable Zsh script.
- deploy-status.zsh
deploy_status() { print -r -- "deploy target=${1:-staging}" } deploy_status "${1:-staging}"
The sample is sourceable so the compiled wordcode path matches how .zwc files are normally used by Zsh.
- Check the script syntax before compiling it.
$ zsh -n deploy-status.zsh
No output from zsh -n means Zsh parsed the script without finding a syntax error.
- Run the plain-text script through source.
$ zsh -fc 'source ./deploy-status.zsh' deploy target=staging
- Compile the script with zcompile.
$ zsh -fc 'zcompile deploy-status.zsh'
zcompile prints no output when compilation succeeds. The default output file for this command is deploy-status.zsh.zwc.
- Inspect the compiled wordcode file.
$ zsh -fc 'zcompile -t deploy-status.zsh.zwc' zwc file (read) for zsh-5.9 deploy-status.zsh
The listed source name confirms that the compiled file contains deploy-status.zsh.
- Source the script again after compilation.
$ zsh -fc 'source ./deploy-status.zsh' deploy target=staging
Re-run zcompile deploy-status.zsh after editing the source file so the .zwc file matches the current script.
- Remove the sample files after testing.
$ rm -f deploy-status.zsh deploy-status.zsh.zwc
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.