Catalog / Zsh Scripting Cheatsheet
Zsh Scripting Cheatsheet
A handy reference for Zsh scripting, covering syntax, built-ins, options, and common patterns.
Zsh Basics & Syntax
Basic Syntax
Comments |
|
Variables |
|
String Concatenation |
|
Command Substitution |
|
Exit Status |
|
Here Documents |
|
Arrays |
|
Conditional Statements
|
String Comparisons: |
File Tests: |
Numeric Comparisons: |
Looping
For Loop:
|
While Loop:
|
Until Loop:
|
Looping through array:
|
Functions & Builtins
Functions
Function Definition |
OR
|
Calling a function |
|
Passing Arguments |
|
Return Value |
|
Local Variables |
|
Useful Built-in Commands
|
Print text to standard output. |
|
Formatted output (similar to C’s |
|
Read input from standard input. |
|
Exit the script. |
|
Execute commands from a file in the current shell. |
|
Print working directory. |
|
Change directory. |
Parameter Expansion
${var:-word} - Use default value ‘word’ if var is unset or null. |
${var:=word} - Assign default value ‘word’ to var if var is unset or null. |
${var:?message} - Display error message and exit if var is unset or null. |
${var:+word} - Use ‘word’ if var is set and not null. |
${#var} - String length of var. |
${var:offset:length} - Substring of var. |
Zsh Options & Globbing
Setting Options
|
Enable option. |
|
Disable option. |
|
Enable option (Zsh specific). |
|
Disable option (Zsh specific). |
Useful Options
allexport: Automatically export all defined variables. |
errexit: Exit immediately if a command exits with a non-zero status. |
nounset: Treat unset variables as an error when substituting. |
xtrace: Print commands and their arguments as they are executed. |
noclobber: Prevent overwriting existing files with redirection. |
Globbing (Filename Generation)
|
Matches any string of characters (except leading dots). |
|
Matches any single character. |
|
Matches one of the characters |
|
Matches any character between |
|
Matches any character except |
|
Matches either |
|
Matches files recursively (Zsh specific, enable with |
Advanced Zsh
Zsh Modules
zmodload zsh/module |
Loads a specific Zsh module. Example: |
Available Modules |
|
Common modules |
zsh/tcp, zsh/datetime, zsh/mathfunc |
Process Substitution
<(command) |
Provides the output of command as a file. |
>(command) |
Redirects standard output to command. |
Customizing the Prompt
PS1 is the primary prompt variable.
|
Common escape sequences: %n (username), %m (hostname), %~ (current directory), %d (current directory full path), %w (current time), %D{format} (date/time with format). |
Example:
|
For advanced prompt customization, use a Zsh theme manager like Oh My Zsh or Prezto. |