zsh Essentials
zsh (the Z shell) is the default shell on macOS and a popular choice on Linux. For everyday commands it behaves
like bash: the same cd, pipes, redirection, $VAR, if/for, &&. Most bash one-liners just work. What zsh
adds is a set of conveniences that make interactive use and small scripts nicer: smarter completion, powerful
globbing, compact parameter expansion and a very configurable prompt.
This lesson covers the differences you notice first. All runnable examples use zsh 5.9, the version macOS ships.
| bash | zsh | |
|---|---|---|
| Array indexes start at | 0 | 1 |
Unquoted $var split into words? |
yes | no |
| Glob with no match | passed on literally (*.xyz) |
error no matches found |
Recursive glob **/*.txt |
needs shopt -s globstar |
built in |
| Print command | echo, printf |
print, echo, printf |
| Options | set -o, shopt |
setopt / unsetopt |
| Startup file | ~/.bashrc |
~/.zshrc |
Arrays start at 1
fruits=(apple banana cherry)
print "first: $fruits[1]"
print "last: $fruits[-1]"
print "count: $#fruits"
print "slice: $fruits[2,3]"
fruits+=(kiwi)
print -l $fruits
typeset -A ages
ages=(ada 36 alan 41)
print "ada is $ages[ada]; sorted keys:" ${(ok)ages}first: apple
last: cherry
count: 3
slice: banana cherry
apple
banana
cherry
kiwi
ada is 36; sorted keys: ada alan
$fruits[1]works without braces (bash needs${fruits[0]}). Negative indexes count from the end.print -lprints each argument on its own line.typeset -Adeclares an associative array (a dictionary).
Globbing and glob qualifiers
zsh's wildcards go further than * and ?. A glob qualifier in parentheses at the end filters the matches by
type, size, permissions or date, which often replaces a find command:
mkdir -p src/lib docs
print "fn main() {}" > src/main.rs
print "pub fn x() {}" > src/lib/util.rs
print "# Notes" > docs/notes.md
print -n "" > empty.log
print "big data here" > big.log
print "recursive: " **/*.rs
print "folders: " *(/)
print "files: " *(.)
print "non-empty: " *.log(L+0)
print "no match: " *.xyz(N)
setopt extendedglob
print "not .log: " ^*.log
print "names only:" src/**/*.rs(:t)recursive: src/lib/util.rs src/main.rs
folders: docs src
files: big.log empty.log
non-empty: big.log
no match:
not .log: docs src
names only: main.rs util.rs
| Qualifier | Matches |
|---|---|
(.) |
regular files |
(/) |
directories |
(@) |
symbolic links |
(*) |
executable files |
(L+10k) / (L-1) |
larger than 10 KB / smaller than 1 byte (L+0 = not empty) |
(mh-2) |
modified in the last 2 hours |
(om[1,3]) |
sorted by modification time, newest 3 |
(N) |
"null glob": no error if nothing matches |
(:t) / (:r) / (:e) |
modifiers: file name only / without extension / extension only |
Without (N), a pattern that matches nothing is an error: zsh refuses to run that command at all, instead of
passing a literal *.bak to it the way bash does. That protects you from surprises like rm *.bak acting on a
file really named *.bak:
print "before"
ls *.bak
print "ls never ran; the script goes on"before
/w/main.zsh:2: no matches found: *.bak
ls never ran; the script goes on
Parameter expansion flags
zsh puts flags in parentheses right after ${ to transform a value. They combine and replace many calls to
tr, cut, sort and sed:
name="ada lovelace"
csv="pear,apple,fig"
print ${(U)name} # upper case
print ${(C)name} # capitalise words
parts=(${(s:,:)csv}) # split on ,
print "${#parts} parts, sorted:" ${(o)parts}
print ${(j: | :)parts} # join with " | "
print ${(Oa)parts} # reverse array order
file="report.final.pdf"
print "${file:r} / ${file:e} / ${file%%.*}"
n=42
print ${(l:6::0:)n} # pad left to 6 with zerosADA LOVELACE
Ada Lovelace
3 parts, sorted: apple fig pear
pear | apple | fig
fig apple pear
report.final / pdf / report
000042
The ${var:r}/${var:e} modifiers (root, extension) work on any variable; ${var%%.*} is the bash-compatible form.
Flags apply to arrays only outside double quotes: inside "..." the array is first joined into one string, so
"${(o)parts}" would not sort anything.
Options with setopt
zsh's behaviour is switched with options. Names are case-insensitive and underscores are ignored, so
setopt AUTO_CD and setopt autocd are the same. Popular ones for ~/.zshrc:
| Option | Effect |
|---|---|
AUTO_CD |
type a folder name to cd into it |
EXTENDED_GLOB |
enables ^pattern, #, ~ in globs |
NULL_GLOB |
patterns with no match vanish instead of erroring |
SHARE_HISTORY |
all open terminals share one history |
HIST_IGNORE_DUPS |
don't store a command twice in a row |
CORRECT |
offer to fix typos in command names |
setopt nullglob
print "matches: [" *.nothing "]"
unsetopt nullglob
words="one two three"
for w in $words; do print "zsh: [$w]"; done
setopt shwordsplit
for w in $words; do print "bash-like: [$w]"; donematches: [ ]
zsh: [one two three]
bash-like: [one]
bash-like: [two]
bash-like: [three]
setopt with no arguments lists the options that differ from the defaults. shwordsplit makes unquoted variables
split like in bash; zsh's own way is ${=words}. When you need full bash or POSIX behaviour for a script,
emulate -L sh inside a function does it.
The prompt
The prompt is the PROMPT variable (alias PS1), and RPROMPT puts text on the right edge. Escapes start with %:
| Escape | Shows |
|---|---|
%n / %m |
user / short host name |
%~ / %1~ |
current folder with ~ / last folder only |
%# |
% for users, # for root |
%? |
exit status of the last command |
%D{%H:%M} |
time (any strftime format) |
%F{green}…%f |
colour on / off |
%(?.ok.fail) |
conditional: ok if the last command succeeded |
PROMPT='%n %1~ %(?.ok.fail) %# '
false
print -P "after false: $PROMPT"
true
print -P "after true: $PROMPT"after false: learner ~ fail %
after true: learner ~ ok %
To show the Git branch, zsh has the vcs_info module; many people use a ready-made theme instead.
Completion, frameworks and plugins
zsh's completion system has to be switched on once in ~/.zshrc (macOS and most frameworks do it for you):
autoload -Uz compinit && compinit
zstyle ':completion:*' menu select # arrow-key menu
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}' # case-insensitiveAfter that, Tab completes options with descriptions (git commit --am<Tab>), branch names, SSH hosts and
kill targets.
- Oh My Zsh is the best-known framework: hundreds of plugins (
git,docker,kubectl) and themes, configured withplugins=(git docker)andZSH_THEME="robbyrussell"in~/.zshrc. It's easy but can make startup slow. - Lighter alternatives: a plugin manager such as zinit or antidote, or no framework at all.
- Must-have plugins: zsh-autosuggestions (grey suggestions from history) and zsh-syntax-highlighting.
- Prompt engines like Starship or Powerlevel10k give a fast, informative prompt in a few lines of config.
ada@macbook ~ % brew install zsh-autosuggestions starship
ada@macbook ~ % echo 'source $(brew --prefix)/share/zsh-autosuggestions/zsh-autosuggestions.zsh' >> ~/.zshrc
ada@macbook ~ % echo 'eval "$(starship init zsh)"' >> ~/.zshrcLearn more: The Terminal on macOS, Aliases & Profiles, Shells Compared.
Test yourself
With a=(x y z) in zsh, what does print $a[1] show?
- x
- y
- nothing
- x y z
Which zsh glob lists only directories in the current folder?
- *(.)
- *(/)
- *(@)
- */**
What happens in zsh (default options) when you run rm *.bak and no .bak files exist?
- rm deletes a file literally named *.bak
- zsh reports 'no matches found' and doesn't run rm
- All files are deleted
- The pattern is silently removed and rm runs with no arguments