Dev tools and workflow · Beginner · 16 min
Get more from zsh with history, aliases, functions and completion
By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · zsh 5.9 (Ubuntu package 5.9-8ubuntu3)
You will write your own ~/.zshrc from an empty file, with shared history, useful options, aliases and functions, menu completion, a prompt that shows the Git branch and a way to measure how long it takes to start.
On this page
zsh is the shell you type commands into on a Mac, and it is one apt install away on Ubuntu. Out of the box it behaves much like bash. The parts that make it pleasant to live in, such as history shared between terminals, a completion menu you can move through with the arrow keys, and a prompt that tells you which Git branch you are on, are all switched off until your ~/.zshrc turns them on.
Many people get those features by installing a framework with hundreds of files. This tutorial does the opposite: you write a config of about 60 lines yourself, one section at a time, and check each section before adding the next. You end up knowing what every line does, the shell starts fast, and nothing needs downloading beyond zsh itself. That matters if you work on prepaid data, or in Termux on an Android phone, where pkg install zsh gives you the same shell and the same config works.
You build the config in a throwaway folder, ~/zsh-demo, and point zsh at it with the ZDOTDIR variable, so your current shell setup is not touched until the last step.
Step 1 · Install zsh
On Ubuntu, install zsh and Git:
sudo apt update
sudo apt install -y zsh git
zsh --versionUbuntu 26.04 ships zsh 5.9, so the last command prints something like zsh 5.9 (x86_64-ubuntu-linux-gnu). macOS already has zsh 5.9 at /bin/zsh. Upstream has since published 5.9.1 and 5.9.2, which are bug-fix releases; everything here works the same on them.
Check it worked
command -v zshThe output is a path such as /usr/bin/zsh (or /bin/zsh on a Mac).
Step 2 · Start a config in a safe place
zsh reads its startup files from the folder named in ZDOTDIR, or from your home folder when that is not set. Two files matter here. .zshenv is read by every zsh, including scripts, so it stays tiny. .zshrc is read only by interactive shells, the ones you type into, and holds everything else.
Create the folder and a .zshenv:
mkdir -p ~/zsh-demo
cat > ~/zsh-demo/.zshenv <<'EOF'
# Ubuntu's /etc/zsh/zshrc runs compinit for you unless this is set.
# The .zshrc below runs it once, with its own settings.
skip_global_compinit=1
EOFUbuntu and Debian add a system-wide /etc/zsh/zshrc that already calls compinit, the function that sets up completion. If your own config calls it too, the work is done twice on every new terminal. skip_global_compinit=1 turns the system copy off. It does nothing on a Mac.
Now start the .zshrc:
cat > ~/zsh-demo/.zshrc <<'EOF'
# ~/.zshrc, written by hand, one section at a time.
EOFTo try the config at any point, open a zsh that reads it, and type exit to come back:
ZDOTDIR="$HOME/zsh-demo" zshFor the checks in this tutorial you also use zsh -ic '<command>': -i makes the shell interactive, so it reads .zshrc, and -c runs one command and exits.
Check it worked
ZDOTDIR="$HOME/zsh-demo" zsh -ic 'print -r -- "config from $ZDOTDIR"'The output is config from /home/<you>/zsh-demo, with your own user name.
Step 3 · Keep more history and share it between terminals
On Ubuntu, zsh keeps 30 commands in memory and saves none of them to a file until you tell it where to write (macOS's system /etc/zshrc sets a small history file for you, but this section replaces its limits with larger ones). Append a history section:
cat >> ~/zsh-demo/.zshrc <<'EOF'
# History
HISTFILE=${ZDOTDIR:-$HOME}/.zsh_history
HISTSIZE=50000 # lines kept in memory
SAVEHIST=50000 # lines kept in the file
setopt EXTENDED_HISTORY # save when each command started and how long it ran
setopt SHARE_HISTORY # write each command at once, read new ones from other terminals
setopt HIST_IGNORE_ALL_DUPS # an older copy of a repeated command is removed
setopt HIST_IGNORE_SPACE # a command typed with a leading space is not saved
setopt HIST_REDUCE_BLANKS # tidy extra spaces before saving
setopt HIST_VERIFY # !! and !$ fill the line for you to check, not run at once
EOF${ZDOTDIR:-$HOME} means "the ZDOTDIR folder if it is set, otherwise home", so the same line works now and after you move the file into place. SHARE_HISTORY already appends to the file as you go, so do not also set INC_APPEND_HISTORY; the zsh manual says to choose one.
HIST_IGNORE_SPACE is the one to remember for anything sensitive. If you ever have to type a command that includes a token, start it with a space and it stays out of the file. Better still, keep tokens in files or environment variables and never type them at all.
Check it worked
ZDOTDIR="$HOME/zsh-demo" zsh -ic 'print -r -- $HISTSIZE; setopt | grep hist'The output is 50000, followed by a list that includes extendedhistory, histignorealldups, histignorespace, histreduceblanks, histverify and sharehistory. setopt with no arguments lists options that are not at their default, in lower case without underscores.
Now see the file fill up. Open the demo shell, run two or three commands such as echo hello from zsh and ls, then type exit, and look at the end of the history file:
tail -n 3 ~/zsh-demo/.zsh_history
grep -q 'echo hello from zsh' ~/zsh-demo/.zsh_historyEach line looks like : 1795718379:0;echo hello from zsh: the time the command started, in seconds since 1970, how many seconds it ran, then the command. To see sharing at work, open two demo shells side by side, run a command in one, press Enter on an empty line in the other, then press the Up arrow there. The command from the first terminal is there.
Step 4 · Turn on options for moving around
A handful of options change how you move between folders. Append them:
cat >> ~/zsh-demo/.zshrc <<'EOF'
# Moving around
setopt AUTO_CD # type a folder name on its own to cd into it
setopt AUTO_PUSHD # every cd pushes the old folder onto a stack
setopt PUSHD_IGNORE_DUPS # no folder appears twice on the stack
setopt PUSHD_SILENT # do not print the stack after each cd
setopt INTERACTIVE_COMMENTS # allow # comments on the command line
DIRSTACKSIZE=10
EOFWith AUTO_CD, typing /etc or .. and pressing Enter changes folder, with no cd. It works only on lines you type, not in scripts or zsh -c, which is what you want: scripts should always say cd.
AUTO_PUSHD gives you a short memory of where you have been. dirs -v lists it with numbers, and cd -2 jumps back to entry 2. Typing cd - and pressing Tab shows the list as a menu once completion is on, which is the next step but one.
Check it worked
ZDOTDIR="$HOME/zsh-demo" zsh -ic 'cd /tmp; cd /etc; cd /usr; dirs -v'
ZDOTDIR="$HOME/zsh-demo" zsh -ic 'cd /tmp; cd /etc; cd /usr; dirs -v' | grep -q '^1[[:space:]]*/etc$'The output is the stack, newest first. The last entry is the folder you started in, shown here as ~ because this run started in your home folder:
0 /usr
1 /etc
2 /tmp
3 ~In the demo shell, type /etc on its own, press Enter, and the prompt shows you are in /etc.
Step 5 · Add aliases, and functions where an alias is the wrong tool
An alias replaces the first word of a command with some text before the line runs. It suits short names for commands you type often, where your own arguments go at the end:
cat >> ~/zsh-demo/.zshrc <<'EOF'
# Aliases: short names, arguments go on the end
alias ll='ls -lah'
alias gs='git status --short --branch'
alias gl='git log --oneline --graph --decorate -20'
EOFll /var/log becomes ls -lah /var/log. That is all an alias can do. It has no idea what arguments are, so $1 inside an alias does not mean "the first argument", and it cannot run two steps that both need the same value. The moment you want any of that, write a function instead. Functions take arguments as $1, $2 and "$@", can hold local variables, and return a status like any command:
cat >> ~/zsh-demo/.zshrc <<'EOF'
# Functions: anything that needs its arguments
mkcd() {
mkdir -p -- "$1" && cd -- "$1"
}
bak() {
local f
for f in "$@"; do
cp -p -- "$f" "$f.$(date +%Y%m%d-%H%M%S).bak" || return
done
}
EOFmkcd new-folder makes a folder and moves into it. bak notes.txt copies a file to something like notes.txt.20261118-101500.bak before you edit it. The -- stops a name that begins with - from being read as an option.
Two habits help. Run type ll or type mkcd when you are not sure what a name is, and type command ls (or \ls) to run the real command and skip an alias of the same name.
Check it worked
cd ~/zsh-demo
echo "first draft" > notes.txt
ZDOTDIR="$HOME/zsh-demo" zsh -ic 'type ll; type mkcd; mkcd ~/zsh-demo/new/inner && pwd; cd ~/zsh-demo && bak notes.txt'
ls ~/zsh-demo/notes.txt.*.bakThe output starts with ll is an alias for ls -lah and mkcd is a shell function from /home/<you>/zsh-demo/.zshrc, then the path of the new inner folder, then the name of one backup file.
Step 6 · Turn on completion with a menu
zsh's completion knows the options and subcommands of hundreds of programs, including Git, apt, ssh and systemctl, but it stays off until compinit runs. Append:
cat >> ~/zsh-demo/.zshrc <<'EOF'
# Completion
autoload -Uz compinit
compinit -d "${ZDOTDIR:-$HOME}/.zcompdump"
zmodload zsh/complist
zstyle ':completion:*' menu select
zstyle ':completion:*' matcher-list 'm:{a-z}={A-Za-z}'
zstyle ':completion:*:descriptions' format '%B%d%b'
zstyle ':completion:*' group-name ''
EOFLine by line: autoload loads the compinit function, and compinit sets up the completion system and saves a cache (the .zcompdump file) so later starts are quicker. zsh/complist adds the menu you can move through. menu select opens that menu when there is more than one match. The matcher-list line makes lower-case letters match upper-case ones, so cd doc then Tab finds Documents. The last two lines give each group of matches a bold heading, such as "local branch" or "remote branch" when you complete git switch.
zstyle is how you configure completion. The quoted pattern says which completions a setting applies to, and :completion:* means all of them.
Check it worked
ZDOTDIR="$HOME/zsh-demo" zsh -ic 'print -r -- "git completer: $_comps[git]"'
ZDOTDIR="$HOME/zsh-demo" zsh -ic 'print -r -- $_comps[git]' | grep -qx _gitThe output is git completer: _git, which shows the completion functions are loaded. If it prints git completer: with nothing after it, compinit did not run; check the section was appended to ~/zsh-demo/.zshrc. Now try it by hand in the demo shell:
- Type
git swand press Tab. It completes togit switch. - Type
cd /u/lo/band press Tab. zsh expands each part and the line becomescd /usr/local/bin/. - Type
ls /etc/and press Tab twice. A menu opens. Move with the arrow keys, press Enter to choose, or Ctrl-C to leave it.
Step 7 · Show the Git branch in your prompt
zsh ships a helper called vcs_info that finds out which branch you are on, and a hook system that runs it before each prompt. Append:
cat >> ~/zsh-demo/.zshrc <<'EOF'
# Prompt: folder, Git branch, and a red % or # after a failed command
autoload -Uz vcs_info add-zsh-hook
zstyle ':vcs_info:*' enable git
zstyle ':vcs_info:git:*' formats ' (%b)'
zstyle ':vcs_info:git:*' actionformats ' (%b|%a)'
add-zsh-hook precmd vcs_info
setopt PROMPT_SUBST
PROMPT='%F{blue}%~%f${vcs_info_msg_0_} %(?.%#.%F{red}%#%f) '
EOFadd-zsh-hook precmd vcs_info runs vcs_info before each prompt is drawn, and it stores the result in vcs_info_msg_0_. %b is the branch, and %a is an action in progress such as rebase or merge, which actionformats shows when there is one. PROMPT_SUBST lets the prompt contain ${...}, and the single quotes around PROMPT mean the variable is read each time, not once.
The rest are prompt codes: %~ is the current folder with your home shown as ~, %F{blue} and %f start and stop a colour, and %(?.A.B) shows A when the last command succeeded and B when it failed. %# is % for a normal user and # for root.
Make a small repository to see it:
mkdir -p ~/zsh-demo/repo
cd ~/zsh-demo/repo
git init -b main
git commit --allow-empty -m "First commit"
git switch -c feature/loginCheck it worked
ZDOTDIR="$HOME/zsh-demo" zsh -ic 'cd ~/zsh-demo/repo && vcs_info && print -r -- "[$vcs_info_msg_0_]"'
ZDOTDIR="$HOME/zsh-demo" zsh -ic 'cd ~/zsh-demo/repo && vcs_info && print -r -- "$vcs_info_msg_0_"' | grep -q 'feature/login'The first line prints [ (feature/login)]. In the demo shell, cd ~/zsh-demo/repo and the prompt reads ~/zsh-demo/repo (feature/login) %, with the folder in blue, then the branch and % in the normal colour. Run false, and the % turns red.
Step 8 · Measure how long the shell takes to start
A new terminal should be ready in well under a tenth of a second. When it is not, the cause is nearly always one line in .zshrc: a version manager such as nvm that does a lot of work when it loads, compinit running twice, or a command that reaches the network. zsh can tell you which. Add a switch to .zshenv that loads the profiler, and one at the end of .zshrc that prints its report:
cat >> ~/zsh-demo/.zshenv <<'EOF'
if [[ -n $ZSH_PROFILE ]]; then zmodload zsh/zprof; fi
EOF
cat >> ~/zsh-demo/.zshrc <<'EOF'
# Startup profile: run with ZSH_PROFILE=1 to see what is slow
if [[ -n $ZSH_PROFILE ]]; then zprof | head -n 12; fi
EOF.zshenv runs first, so the profiler is loaded before anything in .zshrc and sees all of it. Without ZSH_PROFILE set, both lines do nothing. They use if ... fi rather than [[ ... ]] && ... on purpose: a && line whose test fails returns status 1, and as the last line of .zshrc that would become the status of every new shell, so the prompt would show a red % before you had run anything.
Time a start, then see where the time went:
time ZDOTDIR="$HOME/zsh-demo" zsh -ic exit
ZSH_PROFILE=1 ZDOTDIR="$HOME/zsh-demo" zsh -ic exitCheck it worked
ZSH_PROFILE=1 ZDOTDIR="$HOME/zsh-demo" zsh -ic exit | grep compinittime reports a real figure, usually a few hundredths of a second for this config. The profile is a table of functions, slowest first, and compinit with its helper compaudit is at or near the top. The calls column for compinit should say 1. If you see 2, it is running twice; on Ubuntu that means skip_global_compinit=1 is missing from .zshenv. Run the time command a second time too: the first start after a change rebuilds the completion cache and is slower.
Step 9 · Make it your everyday shell
When you are happy with the demo, put the two files where zsh looks by default.
This replaces ~/.zshrc and ~/.zshenv if you have them, so the first two commands keep dated copies. If you already have a config you like, compare the files and merge by hand instead.
if [ -e ~/.zshrc ]; then cp -p ~/.zshrc ~/.zshrc.before-demo-"$(date +%Y%m%d)"; fi
if [ -e ~/.zshenv ]; then cp -p ~/.zshenv ~/.zshenv.before-demo-"$(date +%Y%m%d)"; fi
cp ~/zsh-demo/.zshrc ~/.zshrc
cp ~/zsh-demo/.zshenv ~/.zshenvOn Ubuntu, make zsh your login shell. chsh asks for your password, and the change takes effect the next time you log in or open a new terminal window:
chsh -s "$(command -v zsh)"A Mac already uses zsh. Then remove the practice folder, which also holds the demo history and the test repository:
cd ~
rm -rf ~/zsh-demoCheck it worked
zsh -ic 'print -r -- $HISTFILE; type mkcd'The output is /home/<you>/.zsh_history and mkcd is a shell function from /home/<you>/.zshrc. After you log in again, echo $SHELL prints the path to zsh.
The same ideas in bash
If you also use bash on servers you do not control, most of this has a bash form in ~/.bashrc:
- History:
HISTSIZE=50000,HISTFILESIZE=50000,HISTCONTROL=ignoreboth:erasedups(leading space and duplicates),shopt -s histappend, andPROMPT_COMMAND='history -a; history -n'to share between terminals. - Moving around:
shopt -s autocdworks as in zsh. bash haspushd,popdanddirs -v, butcddoes not push for you. - Aliases and functions: the same syntax works in both shells, so
mkcdandbakcan be copied over as they are. - Completion: install the
bash-completionpackage, which Ubuntu's default.bashrcloads. - Git branch in the prompt: source
git-prompt.shfrom Git'scontrib/completionfolder and put$(__git_ps1 " (%s)")inPS1.
Next steps
- Search the history you are now saving with a fuzzy finder: search files and history interactively with fzf.
- Keep
.zshrcin a Git repository and link it onto every machine: manage your dotfiles with Git and GNU Stow. - Keep long jobs alive when SSH drops: keep terminal sessions running on a server with tmux.
- Go back over pipes, redirection and exit codes: use the terminal as a programmer.
Related tutorials
- Work on two branches at once with git worktreeYou will fix an urgent bug in a second working tree without stashing your half-finished feature, merge the fix, and clean up every extra tree afterwards.
- Version releases with semantic versioning, Git tags and a changelogYou will take a small shell library from 1.0.0 to 1.1.0 with written version rules, Conventional Commits, a Keep a Changelog file, annotated Git tags, a build stamped by git describe and release notes drafted from the commits since the last tag.
- Search files and shell history interactively with fzfYou will have fzf 0.75 wired into your shell for history search, file insertion and directory jumps, fed by fd with a preview pane, plus two small pickers that switch Git branches and stop processes.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials