Zsh variables, called parameters in the zshparam manual, give names to values a command line or script needs to reuse. They keep labels, counts, paths, and temporary environment settings in one place instead of repeating the same literal through several commands.
A scalar parameter is assigned with name=value and expanded with $name or ${name}. The typeset builtin declares parameters explicitly and can add attributes such as integer handling, while export marks selected scalar values for child process environments.
Values set in one shell stay in that shell unless they are exported. Use braces when a suffix touches the parameter name, quote expansions that must stay one argument, and use unset when a temporary parameter should no longer affect later commands.
Related: How to use arrays in Zsh
Related: How to manage PATH with the Zsh path array
Related: Use variables in Bash scripts
Steps to use variables in Zsh:
- Create a script that declares variables, exports one value, and removes it after use.
- vars-demo.zsh
#!/usr/bin/env zsh emulate -L zsh setopt err_exit typeset job="nightly backup" typeset -i tries=3 log="${job}-${tries}.log" export MODE=staging print -r -- "job=$job" print -r -- "tries=$tries" print -r -- "log=$log" zsh -fc 'print -r -- "child=$MODE"' unset MODE print -r -- "after=${MODE-unset}"
emulate -L zsh resets option behavior to native Zsh for this script scope. The -i attribute stores tries as an integer, and export copies MODE into child process environments.
- Check the script syntax before running it.
$ zsh -n vars-demo.zsh
No output means Zsh parsed the assignments, expansions, and unset command without finding a syntax error.
- Run the script and confirm each expansion.
$ zsh vars-demo.zsh job=nightly backup tries=3 log=nightly backup-3.log child=staging after=unset
The child shell sees MODE because it was exported. The final line shows that unset MODE removed the parameter from the parent script before the last expansion.
- Use braces when text touches the end of the parameter name.
$ prefix=nightly $ print -r -- "${prefix}_report" nightly_reportWithout braces, $prefix_report would ask for a different parameter named prefix_report instead of appending _report to $prefix.
- Quote scalar expansions when a command should receive the value as one argument.
print -r -- "job=$job"
Native Zsh does not split scalar parameters on spaces by default, but compatibility options such as sh_word_split can change that behavior. Quoted expansions keep the script's argument boundary explicit.
- Remove the sample script after testing.
$ rm -f vars-demo.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.