← Back to Index

ZSH Reference

0. Basics

0.1 Hello World

#!/bin/zsh
# echo prints strings to STDOUT and appends a newline
echo "Hello, World!"
TERMINAL OUTPUT
Hello, World!

0.2 Building & Running

ZSH is a command shell. Execute scripts by setting the executable bit or by calling the zsh interpreter.

# Execute a ZSH script directly
zsh script.zsh
TERMINAL OUTPUT
Hello, World!

0.3 Comments

# Single-line comment for annotations and notes
TERMINAL OUTPUT
(No output)

0.4 Imports

ZSH uses modules to extend its core functionality.

# Load the datetime module for advanced time handling
zmodload zsh/datetime
# Load the zparseopts module for CLI argument parsing
zmodload zsh/zparseopts
# Load the net/tcp module for network operations
zmodload zsh/net/tcp
TERMINAL OUTPUT
(No output)

0.5 Exit Codes

# Exit the current shell or script with a status code
# 0 for success, non-zero for error
exit 1 
TERMINAL OUTPUT
(Process exits with status 1)

0.6 Error Handling

# Define a special function to catch and handle command errors
TRAPERR() {
    echo "An error occurred during execution"
}
TERMINAL OUTPUT
(No output)

1. Environment, Variables & Time

1.1 Variable Declaration

x="Value"       # Dynamic string variable
readonly PI=3.14 # Immutable constant
integer num=5    # Explicitly typed integer
float val=3.1    # Explicitly typed floating point
TERMINAL OUTPUT
(No output)

1.2 Integer Types & Limits

ZSH supports 64-bit integers and native floating-point arithmetic.

# Print the maximum 64-bit signed integer value
echo $((9223372036854775807))
TERMINAL OUTPUT
9223372036854775807

1.3 Casting

Casting is performed via variable assignment to a typed variable or within arithmetic context.

integer i=10
# Explicitly cast integer value to float
float f=$i
TERMINAL OUTPUT
(No output)

1.4 Environment Variables

# Export variable to environment for child processes
export API_KEY="secret"
# Access system-wide PATH variable
echo $PATH
TERMINAL OUTPUT
/usr/bin:/bin:/usr/sbin:/sbin (example)

1.5 Time Measurement & Formatting

zmodload zsh/datetime

# High-resolution time measurement using EPOCHREALTIME
start=$EPOCHREALTIME
sleep 1
elapsed=$(( EPOCHREALTIME - start ))

# Format the current time using strftime
strftime "%Y-%m-%d %H:%M:%S" $EPOCHSECONDS
# Format current time as UTC ISO 8601
strftime -u "%Y-%m-%dT%H:%M:%SZ" $EPOCHSECONDS 
TERMINAL OUTPUT
2024-05-16 12:00:00 (example)
2024-05-16T12:00:00Z (example)

2. Operators & Regex

2.1 Arithmetic & Logic

ZSH supports floating point math natively within (( )).

val=$((10 / 3.0)) # Result: 3.333333333
res=$((10 % 3))   # Result: 1 (remainder)
((x++))           # Post-increment variable x
TERMINAL OUTPUT
(No output)

2.2 Regex & Pattern Matching

Native regex matching in [[ ]] using the =~ operator. Results are stored in the $match array.

text="Price: $100"
# Match '$' followed by digits
if [[ $text =~ '\$([0-9]+)' ]]; then
    echo $match[1] # Print first capture group: "100"
fi
TERMINAL OUTPUT
100

3. Argument Parsing

3.1 Argument Parsing

Using the powerful zparseopts module.

zmodload zsh/zparseopts

# v: flag, o: valued flag, tags+: flag that can appear multiple times
zparseopts -D -E v=verbose o:=output -tags+:=tags

# Check if verbose flag was provided
v_set=${#verbose}
# Extract value from output flag array
o_val=${output[2]}
TERMINAL OUTPUT
(No output)

4. Functions & Memory

4.1 Declaration & Returns

# Define function logic
add() {
    local a=$1 # Positional parameters
    local b=$2
    # Output result to STDOUT to "return" value
    echo $(( a + b )) 
}

# Call function and capture result
result=$(add 10 20)
echo $result
TERMINAL OUTPUT
30

4.2 References & Pointers

ZSH supports indirect referencing using the (P) parameter expansion flag.

increment() {
    local var_name=$1
    # Evaluate the content of var_name as a variable name and increment it
    (( ${(P)var_name}++ )) 
}

val=10
increment val
echo $val
TERMINAL OUTPUT
11

5. Control Flow

5.1 Conditionals (If/Else)

x=10
# Standard if/elif/else
if [[ $x -gt 10 ]]; then
    echo "Greater"
elif [[ $x -eq 10 ]]; then
    echo "Equal"
else
    echo "Lesser"
fi

# Arithmetic truthiness: non-zero is true in (( ))
if (( 1 )); then echo "Math true"; fi

# Shell success check: 0 is success (true)
if true; then echo "Success"; fi
TERMINAL OUTPUT
Equal
Math true
Success

5.2 Switch / Case

val="yes"
case $val in
    yes|y) echo "Confirmed" ;;
    no|n)  echo "Denied" ;;
    *)     echo "Unknown" ;;
esac
TERMINAL OUTPUT
Confirmed

5.3 Basic Loops (While/For)

# Loop through a brace-expanded range
for i in {0..2}; do echo -n $i; done

x=0
# while loop using arithmetic condition
while (( x < 3 )); do
    echo -n $x
    ((x++))
done
TERMINAL OUTPUT
012012

5.4 Breaking & Continue

for x in {1..5}; do
    if (( x == 2 )); then continue; fi # Skip to next iteration
    if (( x == 4 )); then break; fi    # Exit loop immediately
    echo -n $x
done
TERMINAL OUTPUT
13

5.5 Iterating Collections

# Iterate over elements of an array (ZSH is 1-indexed)
list=("a" "b")
for val in $list; do echo -n $val; done

# Iterate over keys of an associative array
typeset -A map=(["id"]="42")
for k in ${(k)map}; do 
    echo -n " $k:$map[$k]"
done
TERMINAL OUTPUT
ab id:42

6. Strings & Files

6.1 String Manipulation

s="hello world"
echo $#s           # String length (11)
echo $s[1,5]       # Substring from index 1 to 5 (1-based: "hello")
echo ${s/world/zsh} # Replace "world" with "zsh"
TERMINAL OUTPUT
11
hello
hello zsh

6.2 Path Joining

ZSH features powerful built-in modifiers for path manipulation.

p="/usr/local/bin/file.txt"
echo $p:h # Head: Directory portion ("/usr/local/bin")
echo $p:t # Tail: Filename portion ("file.txt")
echo $p:e # Extension portion ("txt")
TERMINAL OUTPUT
/usr/local/bin
file.txt
txt

6.3 Streaming I/O (Chunks)

# Read file line by line using the read builtin
while read -r line; do
    echo "Line: $line"
done < data.txt
TERMINAL OUTPUT
(Output depends on data.txt content)

6.4 Read to Memory

# Read the entire contents of a file into a variable
content=$(<file.txt)
TERMINAL OUTPUT
(No output)

7. Binary & Bitwise

7.1 Allocation & Packing

ZSH does not provide native binary packing modules. Use external tools like xxd.

# Hex output using printf
printf '\x42\x00'
TERMINAL OUTPUT
B (followed by a null byte)

7.2 Bitwise Operations

res=$((0b1010 & 0b1100)) # Bitwise AND
res=$((0b1010 | 0b1100)) # Bitwise OR
res=$((0b1010 ^ 0b1100)) # Bitwise XOR
res=$((~0b1010))         # Bitwise NOT (complement)
res=$((0b0001 << 2))     # Bitwise Shift Left (0b0100)
TERMINAL OUTPUT
(No output)

7.3 Hex Conversion

# Format decimal integer as 2-digit hex
printf '%02x\n' 255
TERMINAL OUTPUT
ff

8. Collections & JSON

8.1 Lists, Maps & Sets

# List (Indexed Array - 1-based indexing)
l=(1 2); l+=(3)

# Map (Associative Array)
typeset -A m; m=(key val)

# Set (Unique Array - duplicates automatically removed)
typeset -U s; s=(1 1 2)
TERMINAL OUTPUT
(No output)

8.2 JSON Parsing

Like Bash, ZSH relies on external utilities for JSON.

# Extract values using jq
echo '{"id":42}' | jq '.id'

# High-precision math using bc
echo "scale=4; 10/3" | bc
TERMINAL OUTPUT
42
3.3333

9. Systems & Networking

9.1 TCP Server & Client

ZSH includes built-in support for TCP via the zsh/net/tcp module.

zmodload zsh/net/tcp
# Connect to remote host on port 80
ztcp example.com 80
fd=$REPLY # REPLY contains the file descriptor
# Send HTTP request through the socket
echo "GET / HTTP/1.0\r\n\r\n" >&$fd
# Read response line
read -u $fd line
# Close the TCP connection
ztcp -c $fd
TERMINAL OUTPUT
(No output)

9.2 UDP Server & Client

ZSH does not support UDP natively via modules.

# Use external 'nc' (netcat) for UDP operations
echo "ping" | nc -u -w1 127.0.0.1 8080
TERMINAL OUTPUT
(No output)

9.3 Concurrency

# Execute command in the background
command &
# Wait for the last background process to complete
wait $!
TERMINAL OUTPUT
(No output)

9.4 SQLite

# Execute SQL query using the sqlite3 CLI tool
sqlite3 :memory: "SELECT 42;"
TERMINAL OUTPUT
42