ZSH, short for the Z Shell, is one of the most popular Unix shells. It’s known for its rich features and enhancements over other shells like bash. One of the features it inherits from sh and enhances further is variable expansion.
Variable expansion (or parameter expansion) is the mechanism by which the shell expands a variable to its value. This allows users to manipulate and use the value of a variable in various ways.
1. Basic Variable Expansion
At its most basic, variable expansion in ZSH works just like it does in any other Bourne-style shell.
name="ZSH"
echo $name # Outputs: ZSH
2. Curly Braces Expansion
You can use curly braces to clearly delimit a variable’s name:
echo ${name} # Outputs: ZSH
This is especially helpful when appending or prepending strings:
echo "${name} is cool" # Outputs: ZSH is cool
3. Modifiers for Expansion
ZSH comes with a plethora of modifiers to manipulate the string during expansion.
- Length of a Variable: ${#var} will give the length of $var.
echo ${#name} # Outputs: 3
- Substring Expansion: {var:start:length} extracts a substring.
word="expansion" echo ${word:3:4} # Outputs: ansio
- Pattern Replacement: ${var/pattern/replacement} can replace a pattern within the string.
path="/usr/local/bin" echo ${path/bin/sbin} # Outputs: /usr/local/sbin
4. Special Variables
ZSH provides a bunch of special variables that you can expand:
- `$?`: Exit status of the last command.
- `$#`: Number of command line arguments.
- `$*`: All the command line arguments.
- `$$`: The process ID of the ZSH process.
Example:
echo $? # Outputs the exit status of the last command
5. Array Expansion
ZSH has robust array manipulation capabilities:
colors=("red" "green" "blue")
echo $colors[2] # Outputs: green
You can also extract slices from arrays:
echo {colors[@]:1:2} # Outputs: red green
6. Arithmetic Expansion
This allows for arithmetic operations within a $(( )) syntax:
x=5
y=3
echo $((x + y)) # Outputs: 8
7. Command Substitution
With command substitution, the output of a command can be assigned to a variable:
current_dir=$(pwd)
echo $current_dir # Outputs the current directory
8. Nested Expansion
ZSH allows for nested variable expansions:
x="world"
y="hello_$x"
echo ${!y} # Outputs: hello_world
Conclusion
Variable expansion in ZSH provides a powerful way to manipulate and utilize data within the shell. By understanding and utilizing these capabilities, one can write more dynamic, efficient, and concise scripts and commands. The examples above are just the tip of the iceberg; ZSH’s man pages and documentation offer an even deeper dive into these capabilities.