Getting started

Introduction

zsh adds globbing, completion, and line editing on top of bash. This sheet covers those extras; see the Bash cheatsheet for shared syntax.

Startup files

echo $ZDOTDIR     # empty means $HOME
ls ~/.zshenv ~/.zshrc

Read order

FileRuns
.zshenvEvery zsh, including scripts
.zprofileLogin shells, before .zshrc
.zshrcInteractive shells
.zloginLogin shells, after .zshrc
.zlogoutLogin shell exit

See: Startup files

Change default shell

chsh -s $(which zsh)
echo $SHELL      # verify
exec zsh         # switch now

chsh changes the login shell; $SHELL updates after you log in again.

See: man chsh

Bash compatibility

setopt shwordsplit  # split unquoted $var
emulate sh -c 'echo hi'

zsh keeps unquoted parameters as one word and indexes arrays from 1.

See: Shell emulation

Clean shell

zsh -f     # no startup files
zsh -d     # no global rcs
exec zsh   # restart

-f also skips .zshenv; -d skips /etc/zsh*. Use either when debugging a broken config.

See: Invocation

Globbing

Recursive globs

ls **/*.js          # any depth
setopt globdots     # * matches dotfiles too
ls **/*.js(N)       # N: drop if no match

**/ works with no options; globdots makes wildcards match leading dots.

See: Filename generation

Qualifiers

ls *(.)           # regular files only
ls *(m0)          # modified today
ls *(m-4)         # modified within 4 days
ls *(om[1,3])     # three newest files

Qualifiers

QualifierMatches
(.)Regular files
(/)Directories
(@)Symbolic links
(*)Executable plain files
(D)Include dotfiles
(m0)Modified today
(m-1)Modified within 1 day
(m-4)Modified within 4 days
(Lk+100)Larger than 100 KB
(om)Newest first
(On)Names descending
(u:root)Owned by root

Qualifiers combine, as in *(.om[1]) for the newest regular file.

See: Glob qualifiers

Excluding matches

setopt extendedglob
ls ^*.txt          # everything except .txt
ls *.js~test*      # .js files not starting test

Both ^ and ~ need extendedglob. ^ negates a whole pattern; ~ subtracts a pattern.

See: Glob operators

Extended globs

setopt extendedglob
ls (#i)*readme*    # case-insensitive
ls file<1-9>.txt   # one digit
ls a##b            # one or more a's

# repeats the preceding pattern zero or more times, ## one or more. (#b) turns on backreferences for [[ = ]].

See: Globbing flags

Renaming

autoload -Uz zmv
zmv -n '(*).txt' '$1.md'    # dry run
zmv '(*).txt' '$1.md'       # rename
zmv -W '*.txt' '*.md'       # wildcard form

-n prints what would change. -W captures * automatically, so no $1 is needed.

See: zmv

No matches

ls *.nope        # zsh: no matches found
setopt nullglob  # drop unmatched patterns
setopt nonomatch # keep the pattern as typed

The default error stops the whole command; the two options change that.

See: Filename generation

Expansion

Parameter flags

v=a:b:c
print ${(s.:.)v}            # a b c
print ${(j:,:)${(s.:.)v}}   # a,b,c
print ${(U)${(q)v}}         # quoted, uppercase

Flags

FlagEffect
(s:x:)Split on x
(j:x:)Join with x
(f)Split into lines
(z)Split into shell words
(q)Quote for re-entry
(u)Keep unique words
(o)Sort ascending
(O)Sort descending
(k)Keys of a map
(v)Values of a map
(U)Uppercase
(L)Lowercase
(t)Type of a parameter
(l:3::0:)Pad left to width 3 with 0
(r:3::0:)Pad right to width 3 with 0

Flags nest inside-out: the inner expansion runs first.

See: Parameter expansion

Nested expansion

lines=$'one\ntwo\nthree'
print ${${(f)lines}[2]}      # two
arr=(c a b)
print ${(j:,:)${(o)arr}}     # a,b,c

Subscripts apply to the result of the braces around them, so nested expansions read from the inside out.

See: Parameter expansion

Modifiers

f=/tmp/archive.tar.gz
print ${f:h}    # /tmp
print ${f:t}    # archive.tar.gz
print ${f:r}    # /tmp/archive.tar
print ${f:gs/tmp/var}  # /var/archive.tar.gz

Modifiers

ModifierEffect
:hDirectory part
:tFilename part
:rStrip extension
:eExtension only
:lLowercase
:uUppercase
:s/a/b/Replace first match
:gs/a/b/Replace every match

Modifiers work on parameters and history references, as in !!:h.

See: Modifiers

Array expansion

arr=(a b c)
print -l $arr          # one word per line
print -l "$arr"        # one word: a b c
print -l "${(@)arr}"   # one word per element
print $arr[2]          # b

Cartesian product

arr=(a b)
print $^arr.txt        # a.txt b.txt

"${(@)arr}" keeps each element a separate word; $^arr joins each element with the text that follows.

See: Array parameters

Word splitting

v="a b"
print -l $v     # a b (one word)
print -l $=v    # a and b
print -l $~v    # v used as a pattern

Unquoted parameters are not split; $= forces splitting and $~ forces pattern interpretation.

See: Parameter expansion

Arrays

Arrays

arr=(one two three)
print $arr[1]      # one
print $arr[-1]     # three
print $arr[2,3]    # two three
print ${#arr}      # 3
arr+=(four)
unset 'arr[2]'

Arrays are 1-indexed. Negative indexes count from the end, and arr+=(x) appends. Deleting an element leaves a gap, so ${#arr} is not the highest index.

See: Array parameters

Subscripts

arr=(foo bar baz)
print $arr[(i)ba*]    # 2, first match
print $arr[(I)ba*]    # 3, last match
print $arr[(r)ba*]    # bar, first value

(i) and (I) return indexes; (r) and (R) return values.

See: Subscript flags

Associative arrays

typeset -A map
map=(host localhost port 8080)
print ${(k)map}     # host port
print ${(v)map}     # localhost 8080
print ${(kv)map}    # host localhost port 8080
print ${(ok)map}    # keys sorted

Declare with typeset -A; ${(kv)map} flattens key/value pairs.

See: Parameters

Attributes

typeset -i n=42        # integer
typeset -F f=1.5       # float
typeset -l lower=ABC   # lowercase
typeset -T PATH path   # tie PATH to array

Attributes

FlagEffect
-aIndexed array
-AAssociative array
-iInteger arithmetic
-FFloating point
-lLowercase on assign
-uUppercase on assign
-xExport to environment
-rRead-only
-TTie scalar to array

Inside functions, local is the same as typeset.

See: Parameters

History

Event designators

sudo !!          # rerun last command
vim !*           # last command's arguments
git add !^       # first argument of last command
cat !$           # last argument of last command
!?ls             # last command containing ls
!-2              # two commands back

zsh expands these when the line is accepted. setopt histverify loads the expansion into the buffer for editing first.

See: Event designators

Substitution

^old^new           # repeat last, old to new
!!:s/a/b/          # first a to b
!!:gs/a/b/         # every a to b
!$:h               # dirname of last argument

^old^new is shorthand for !!:s/old/new/; the :s modifier also works on any event.

See: Modifiers

History file

HISTFILE=~/.zsh_history
HISTSIZE=10000        # in memory
SAVEHIST=10000        # on disk
setopt share_history  # sync across sessions
setopt inc_append_history

share_history imports commands from other sessions as they run; inc_append_history appends each command immediately.

See: Parameters used by the shell

Search and options

history 1          # last command, numbered
fc -l -10          # last ten commands
setopt hist_ignore_dups
setopt hist_ignore_space
setopt hist_verify

Ctrl-R starts incremental search. hist_ignore_space skips commands starting with a space.

See: History options

Completion

Setup

autoload -Uz compinit
compinit
compinit -C        # skip the security check

compinit scans fpath and writes ~/.zcompdump; rerun it after adding completion functions.

See: Completion system

Styles

zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Z}'
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}

Styles are looked up by context pattern; the matcher above ignores case.

See: Completion configuration

Writing completions

_foo() {
  _arguments '-v[verbose]' '1:file:_files'
}
compdef _foo foo

_arguments describes options and their arguments. A file starting with #compdef foo is autoloaded from fpath.

See: Completion functions

Behaviour options

setopt auto_menu
setopt complete_in_word
setopt always_last_prompt
unsetopt beep

Options

OptionEffect
auto_menuTab again cycles matches
complete_in_wordComplete at cursor, not end
always_last_promptKeep prompt above list
beepOff silences the bell

Completion options are plain shell options.

See: Completion options

Line editing

Keymaps

bindkey -e          # emacs bindings
bindkey -v          # vi bindings
bindkey -M vicmd    # list vi command keys
bindkey -l          # list keymaps

-e and -v switch the main keymap; -M selects another for listing.

See: Zle builtins

Binding keys

bindkey '^R' history-incremental-search-backward
bindkey '^[[A' up-line-or-history
bindkey -s '^X^E' 'nvim\n'

Notation

NotationKey
^ACtrl-A
\eEscape
^[[AUp arrow
^X^ECtrl-X then Ctrl-E

bindkey -s binds a string that is inserted into the buffer.

See: Zle builtins

Custom widgets

my-widget() {
  LBUFFER="git status"
  zle reset-prompt
}
zle -N my-widget
bindkey '^G' my-widget

Widgets read and write $LBUFFER and $RBUFFER around the cursor.

See: Zle widgets

Reading keys and input

read -k 1 key       # one keypress
read -q '?Continue? ' && echo yes
vared -p 'Name: ' name

read -k takes a character count and -q returns success for y.

See: read

ZLE options

zle -l              # list widgets
bindkey -L          # list bindings
setopt no_beep

bindkey -L prints the commands that recreate the current bindings.

See: Zle options

Prompt

Prompt variables

PROMPT='%~ %# '
RPROMPT='%T'
PROMPT2='%_ '
PROMPT_EOL_MARK='%B%S%#%s%b'

PROMPT is the main prompt, RPROMPT sits at the right edge, and PROMPT2 shows while a command continues.

See: Prompt expansion

Escapes

PROMPT='%F{green}%~%f %# '
RPROMPT='%? %T'

Escapes

EscapeShows
%~Working directory, with ~
%nUsername
%mHostname
%## for root, else %
%?Exit status
%TTime, HH:MM
%*Time with seconds
%D{...}strftime format
%F{...}Foreground color
%fReset color
%BBold on
%SStandout on
%jBackground job count
%LShell nesting level
%{...%}Literal, zero width

Pairs like %B/%b switch attributes on and off. %D{...} needs the zsh/datetime module.

See: Prompt expansion

Dynamic prompts

setopt prompt_subst
PROMPT='$(date +%H:%M) %~ %# '

prompt_subst runs command and parameter substitution on every redraw.

See: Prompt expansion

Git branch

setopt prompt_subst
autoload -Uz vcs_info
zstyle ':vcs_info:git:*' formats '%b'
precmd() { vcs_info }
PROMPT='%~ ${vcs_info_msg_0_}%# '

vcs_info sets vcs_info_msg_0_; calling it from precmd refreshes the branch before each prompt.

See: vcs_info

Options

Setting options

setopt autocd
unsetopt beep
set -o noclobber
print ${options[autocd]}   # on
setopt                     # list enabled options

Option names ignore case and underscores, so no_beep and nobeep match.

See: Options

Interactive options

setopt autocd extendedglob globdots
setopt hist_ignore_dups share_history

Common options

OptionEffect
autocdType a directory to enter it
correctOffer spelling corrections
extendedglob^, ~, # patterns
globdotsWildcards match dotfiles
hist_ignore_dupsDrop repeated commands
interactive_comments# starts a comment
noclobberBlock > over existing files
prompt_substExpand $(...) in prompts
share_historyShare history between sessions

correct asks before running a word close to a file or command name.

See: Options

Scripting options

setopt err_exit err_return
setopt no_unset pipe_fail
setopt xtrace

These mirror set -e, set -u, pipefail, and set -x. err_return returns from a function on a failed command.

See: Scripts and functions

Emulation

emulate -L zsh
emulate sh -c 'echo $0'
emulate -L sh

emulate -L sets options locally, so changes do not leak to the caller.

See: Shell emulation

Scripting

Shebang

#!/usr/bin/env zsh
emulate -L zsh
setopt extendedglob

Start scripts with emulate -L zsh so user options and aliases do not change behaviour.

See: Invocation

Functions and locals

greet() {
  local name=$1
  typeset -i count=0
  print "$name $count $0 $argv"
}
greet Ada one two

Inside a function $0 is its name, $argv holds its arguments, and $funcstack lists the call chain.

See: Functions

Option parsing

zparseopts -D -E -A opts v f:
print ${opts[-f]}    # value passed to -f

-D removes parsed options from $@, -E keeps scanning past unknown words, and -A fills an associative array keyed by option name.

See: zparseopts

Traps

TRAPZERR() { print "failed: $?" }
TRAPEXIT() { print "bye" }
TRAPINT() { print "interrupted"; return 1 }

TRAPZERR runs on a non-zero status, TRAPEXIT at shell exit, and TRAPINT on Ctrl-C.

See: Trap functions

Hooks

autoload -Uz add-zsh-hook
my_precmd() { print -r -- ready }
add-zsh-hook precmd my_precmd

precmd runs before each prompt, preexec after a command is read, and chpwd after a directory change.

See: Hook functions

Autoloading

fpath=(~/.zfunc $fpath)
autoload -Uz myfunc
myfunc

A file named myfunc in any fpath directory is read on first call.

See: Autoloading

Utilities

Print

print -P '%F{green}%n%f'   # prompt escapes
print -r -- 'a\tb'         # raw, no escapes
print -l a b c             # one per line
print -f '%s\n' a b        # printf formatting

Options

FlagEffect
-PExpand prompt escapes
-rIgnore backslash escapes
-lOne argument per line
-nNo trailing newline
-fUse printf format

-- ends options, so values starting with - print safely.

See: print

Modules

zmodload zsh/datetime
print $EPOCHSECONDS
strftime '%Y-%m-%d' $EPOCHSECONDS
zmodload zsh/mapfile
print ${(f)mapfile[/etc/hosts]}
zmodload              # list loaded modules

zsh/stat adds stat, and zsh/files adds builtin file commands.

See: Modules

Process substitution and multios

diff <(sort a) <(sort b)     # FIFOs
vim =(curl -s example.com)   # temp file
cat <a <b                    # read both
print hi >a >b               # write both
print =ls                    # path to ls

<(cmd) is read-only; =(cmd) is a regular file that programs can rewrite. Multios fan input or output across several redirections.

See: Process substitution

Helpers

autoload -Uz zargs
zargs -n 100 -- **/*.log -- gzip
autoload -Uz zcalc
zcalc -e '2**10'    # 1024

zargs batches a long argument list, like xargs; zcalc evaluates arithmetic, with -f for floats.

See: User contributions

Also see

0 Comments for this cheatsheet. Write yours!