Skip to content
Hands-on IT IT Drills

Day 5: Aliases and functions

Goal: Build your own shortcuts and choose correctly between alias, function and script for each task. · Duration: approx. 60 min · Prerequisite: Day 4

Briefing

  • Alias: pure text substitution at the start of the line. No argument handling, no logic.
  • Function: runs in the current shell. It can cd, set variables, check arguments.
  • Script: its own process with its own language. It lives on the PATH and can also be called by xargs, make, CI and other programs.
  • zsh also knows global aliases (anywhere in the line) and suffix aliases (the file extension decides).
  • Storage in the lab: one topic per file under ~/term-lab/config/zsh/*.zsh. The lab .zshrc loads them all automatically. In real life the folder is called ~/.config/zsh/ (Day 13).
Do I need ...                          -> use
just a shorter way to write it?        -> alias
arguments, if/case, cd, variables?     -> function
another language, called from outside? -> script in ~/term-lab/bin

Drill 1: The first alias

Start the lab shell and change into the project:

~/term-lab/lab
cd ~/term-lab/projekt
alias gl1='git log --oneline -3'
gl1

Expected:

2e4e6aa (HEAD -> main) chore: Config, Manifeste, Report
a57983c feat: Warenkorb und HTTP-Server
1dc0abc init: Projektgerüst

Now once the wrong way, everything on one line:

alias gl2='git log --oneline -3'; gl2

Expected:

zsh: command not found: gl2

Why? zsh substitutes aliases when reading in the line. At that point, gl2 didn’t exist yet. The same applies in files: an alias only takes effect from the next line on.

Look up and remove:

alias gl1
type gl1
unalias gl1 gl2
type gl1

Expected:

gl1='git log --oneline -3'
gl1 is an alias for git log --oneline -3
gl1 not found

Ad-hoc aliases are gone with the shell. They only become permanent in a file (Drill 2).

Save your progress? Sign up for free

Drill 2: Aliases in a module file

cat > ~/term-lab/config/zsh/aliases.zsh <<'EOF'
# aliases.zsh – aliases from Day 5 (Day 6 adds modern tools)
alias ..='cd ..'
alias ...='cd ../..'
alias md='mkdir -p'
alias h='history -10'
alias reload='exec zsh'          # restart the shell instead of "source ~/.zshrc"
alias path='print -l $path'      # PATH line by line

alias g='git'
alias gs='git status -sb'
alias gl='git log --oneline --graph -15'
EOF
reload
type gs gl

Expected:

gs is an alias for git status -sb
gl is an alias for git log --oneline --graph -15

Tip: exec zsh replaces the shell with a fresh one. That’s cleaner than source ~/.zshrc, because no old aliases or functions are left over. ZDOTDIR and LAB are exported, so in the lab reload works like exec ~/term-lab/lab from Day 1.

The complete file with all aliases from Day 5 and 6 is at $BUCH/zsh/aliases.zsh.

Save your progress? Sign up for free

Drill 3: Bypassing aliases and making them visible

Day 6 maps ls to eza. Sometimes you still want the original:

alias ls='eza --group-directories-first'
whence -w ls cd gs
\ls -d cmd
command ls -d cmd
echo =ls

Expected:

ls: alias
cd: builtin
gs: alias
cmd
cmd
/bin/ls
  • \ls and command ls bypass the alias.
  • =ls is a zsh expansion and yields the path of the real program.

What’s behind an alias before you press Enter? Type gs and then ⌃X a:

[lab] projekt % git status -sb

The _expand_alias widget replaces the alias directly in the line. It comes with the completion system, i.e. from compinit on (Day 2). Check:

bindkey | grep _expand_alias

Expected:

"^Xa" _expand_alias

Tip: alias sudo='sudo ' (with a space at the end) makes zsh check the next word for an alias too. Then sudo ll works.

Save your progress? Sign up for free

Drill 4: Global aliases

Global aliases (-g) are substituted anywhere in the line, not just at the start. Ideal for pipe endings you type all the time:

cat >> ~/term-lab/config/zsh/aliases.zsh <<'EOF'

# Global aliases: substituted anywhere in the line
alias -g G='| grep -i'
alias -g L='| less -R'
alias -g H='| head'
alias -g C='| wc -l'
alias -g J='| jq .'
alias -g NE='2>/dev/null'
EOF
reload
grep ERROR logs/app.log C
grep ERROR logs/app.log G checkout H -3

Expected:

      50
2026-10-05T08:06:42 checkout ERROR request_id=r0006 user=u06
2026-10-05T08:16:52 checkout ERROR request_id=r0016 user=u16
2026-10-05T08:26:02 checkout ERROR request_id=r0026 user=u03

The downside: a single capital G is now harmless nowhere.

print -r -- Status G

Expected (shortened):

usage: grep [-abcdDEFGHhIiJLlMmnOopqRSsUVvwXxZz] [-A num] [-B num] [-C[num]]

In quotes ("Status G") nothing happens. So keep global aliases short, uppercase and few.

Save your progress? Sign up for free

Drill 5: Suffix aliases

A suffix alias (-s) makes a file “executable”: if you type just the file name, zsh starts the matching program.

cat >> ~/term-lab/config/zsh/aliases.zsh <<'EOF'

# Suffix aliases: typing a file name opens the file with the program
alias -s md=bat
alias -s log='less +G'
alias -s {json,yaml,yml}=bat
EOF
reload
alias -s
config/app.json

Expected (shortened):

json=bat
log='less +G'
md=bat
yaml=bat
yml=bat
─────┬──────────────────────────────────────────────────────────
     │ File: config/app.json
─────┼──────────────────────────────────────────────────────────
   1 │ {"service":"shop","port":8080,"replicas":3,
   2 │  "features":{"rabatt":false,"newsletter":true}}
─────┴──────────────────────────────────────────────────────────

logs/app.log now jumps straight to the end of the log (+G), q quits less. bat is covered in detail on Day 6.

Save your progress? Sign up for free

Drill 6: The first function – mkcd

An alias can’t cd into an argument that still has to be created. A function can:

cat > ~/term-lab/config/zsh/functions.zsh <<'EOF'
# functions.zsh – shell functions from Day 5

# Create a directory and change into it
mkcd() {
  [[ -n $1 ]] || { print -u2 "usage: mkcd <dir>"; return 2; }
  mkdir -p -- "$1" && cd -- "$1"
}

# n levels up: up 3
up() {
  local n=${1:-1} d=
  [[ $n == <-> ]] || { print -u2 "usage: up [n]"; return 2; }
  repeat $n d+=../
  cd -- "$d"
}

# Backup copy with timestamp: bak file...
bak() {
  local f
  for f in "$@"; do
    cp -p -- "$f" "$f.$(date +%Y%m%d-%H%M%S).bak" && print "✔ $f gesichert"
  done
}
EOF
reload
mkcd /tmp/lab-demo/a/b && pwd
up 2; pwd
mkcd; echo "rc=$?"

Expected:

/tmp/lab-demo/a/b
/tmp/lab-demo
usage: mkcd <dir>
rc=2

The building blocks found in every good function:

  • local keeps variables inside the function. Without local you overwrite global variables.
  • Always quote "$1" and "$@". -- protects against file names that start with -.
  • print -u2 writes errors to stderr. return 2 provides an exit code for && and ||.
  • <-> is a zsh pattern for “digits only”.
cd ~/term-lab/projekt
type mkcd
functions up | head -4

Expected (shortened):

mkcd is a shell function from /Users/du/term-lab/config/zsh/functions.zsh
up () {
    local n=${1:-1} d=
    [[ $n == <-> ]] || {
        print -u2 "usage: up [n]"

Save your progress? Sign up for free

Drill 7: Toolbox – extract, port, please

Three classics found in almost every senior configuration:

cat >> ~/term-lab/config/zsh/functions.zsh <<'EOF'

# Unpack archives, whatever the format
extract() {
  local f
  for f in "$@"; do
    [[ -f $f ]] || { print -u2 "extract: '$f' ist keine Datei"; return 1; }
    case ${f:l} in
      *.tar.gz|*.tgz)   tar -xzf "$f" ;;
      *.tar.bz2|*.tbz2) tar -xjf "$f" ;;
      *.tar.xz|*.txz)   tar -xJf "$f" ;;
      *.tar)            tar -xf "$f" ;;
      *.zip)            unzip -q "$f" ;;
      *.gz)             gunzip -k "$f" ;;
      *.bz2)            bunzip2 -k "$f" ;;
      *)  print -u2 "extract: unbekanntes Format: $f"; return 1 ;;
    esac
  done
}

# Who is listening on port X? (without argument: all TCP listeners)
port() {
  if [[ -n $1 ]]; then
    lsof -nP -iTCP:"$1" -sTCP:LISTEN
  else
    lsof -nP -iTCP -sTCP:LISTEN
  fi
}

# Repeat the last command with sudo – shows it first
please() {
  local last
  last=$(fc -ln -1) || return 1
  print -P "%F{yellow}sudo $last%f"
  read -q "?Ausführen? [y/N] " || { print; return 1; }
  print
  eval "sudo $last"
}
EOF
reload

${f:l} lowercases the name so that ARCHIV.ZIP matches too. Now test:

tar -czf /tmp/lab-cfg.tgz config
mkcd /tmp/lab-x && extract /tmp/lab-cfg.tgz && ls config
extract nix.rar
cd ~/term-lab/projekt

Expected:

app.json  app.yaml
extract: 'nix.rar' ist keine Datei

Start a web server and find it:

python3 -m http.server 8765 >/dev/null 2>&1 &
port 8765
kill %1
port 8765; echo "rc=$?"

Expected (shortened):

COMMAND   PID USER FD   TYPE             DEVICE SIZE/OFF NODE NAME
Python  77787 du    4u  IPv6 0x1833b23dbc67a68      0t0  TCP *:8765 (LISTEN)
rc=1

please fetches the last line from the history and asks first:

ls /var/root
please

Expected (answer n):

Permission denied: /var/root - code: 13
sudo ls /var/root
Ausführen? [y/N] n

Security: please uses eval to run whatever is in the history with root privileges. The confirmation prompt is intentional. Never build a please without confirmation.

Save your progress? Sign up for free

Drill 8: Autoload functions and real scripts

Many functions slow down startup. zsh can load functions only on their first call. One file per function, the file name is the function name:

mkdir -p ~/term-lab/config/zsh/functions
cat > ~/term-lab/config/zsh/functions/gmerged <<'EOF'
# gmerged – local branches already merged into main
git branch --merged "${1:-main}" | grep -vE '^\*|^ *(main|master)$'
EOF
cat >> ~/term-lab/config/zsh/functions.zsh <<'EOF'

# Autoload: functions from their own files, loaded on first call
fpath=("$LAB/config/zsh/functions" $fpath)
autoload -Uz gmerged
EOF
reload
type gmerged
git branch lab-alt && gmerged
type gmerged
git branch -d lab-alt

Expected (shortened):

gmerged is an autoload shell function
  lab-alt
gmerged is a shell function from /Users/du/term-lab/config/zsh/functions/gmerged
Branch lab-alt entfernt (war 2e4e6aa).

You choose a script when other programs should call it or you want Bash semantics. It goes into ~/term-lab/bin, which has been on the PATH since Day 0:

cat > ~/term-lab/bin/loglevels <<'EOF'
#!/usr/bin/env bash
# loglevels – counts log levels (3rd column) in log files
set -euo pipefail
(( $# )) || { echo "usage: loglevels <datei>..." >&2; exit 2; }
awk '{ n[$3]++ } END { for (l in n) printf "%-6s %d\n", l, n[l] }' "$@" | sort
EOF
chmod +x ~/term-lab/bin/loglevels
shellcheck ~/term-lab/bin/loglevels && echo "✔ shellcheck"
loglevels logs/app.log
echo logs/app.log | xargs loglevels | head -1
echo /tmp/lab-y | xargs mkcd

Expected:

✔ shellcheck
DEBUG  50
ERROR  50
INFO   350
WARN   50
DEBUG  50
xargs: mkcd: No such file or directory

The last two lines show the difference: xargs starts programs. The script loglevels is one, the function mkcd lives only in your shell.

Save your progress? Sign up for free

Shortcut table

Key / command Effect Mnemonic
⌃X a expand the alias in the line eXpand alias
\ls, command ls bypass the alias backslash = “raw”
=ls path of the real program “equals” which file
type x, whence -v x alias, function, builtin or file? “what is x?”
functions x source code of a function shows the body
unalias x, unfunction x remove alias or function un- undoes
alias -g, alias -s list global and suffix aliases global, suffix
reload (exec zsh) fresh shell with new config reload

Checkpoint

c() { eval "$2" >/dev/null 2>&1 && echo "✔ $1" || echo "✘ $1"; }
c "Alias gs"             '[[ $(whence -w gs) == "gs: alias" ]]'
c "globaler Alias G"     '(( ${+galiases[G]} ))'
c "Suffix-Alias json"    '(( ${+saliases[json]} ))'
c "Funktion mkcd"        '[[ $(whence -w mkcd) == "mkcd: function" ]]'
c "mkcd ohne Argument"   '! mkcd'
c "extract, port, please" 'whence extract port please'
c "Autoload gmerged"     '(( ${fpath[(I)*config/zsh/functions]} ))'
c "Skript loglevels"     '[[ -x $LAB/bin/loglevels ]] && shellcheck $LAB/bin/loglevels'

Expected: eight lines with ✔.

Challenge

Write a function gcd that jumps to the root directory of the current Git repo and, outside a repo, aborts with exit code 1 and a message. Test it from ~/term-lab/projekt/internal/cart.

Hint: git rev-parse --show-toplevel returns the root; an alias isn’t enough here, because you have to handle an error case.

Solution

cat >> ~/term-lab/config/zsh/functions.zsh <<'EOF'

# Jump to the root directory of the Git repo
gcd() {
  local root
  root=$(git rev-parse --show-toplevel 2>/dev/null) \
    || { print -u2 "gcd: kein Git-Repo"; return 1; }
  cd -- "$root"
}
EOF
reload
cd ~/term-lab/projekt/internal/cart && gcd && pwd
cd /tmp && gcd; echo "rc=$?"

Expected (shortened):

/Users/du/term-lab/projekt
gcd: kein Git-Repo
rc=1

Save your progress? Sign up for free

Enterprise Note

  • Aliases are personal. In scripts, Makefiles, CI jobs and runbooks, always write out the full commands.
  • Don’t override standard commands with different behavior (rm='rm -i' trains you to be careless on other servers that don’t have this alias).
  • Team tools belong in a repo as scripts with shellcheck in CI, not as functions in your .zshrc.
  • Manage and version shared configurations like ~/.config/zsh/*.zsh with chezmoi (Day 13).
  • No secrets in aliases or functions. Tokens come from the Keychain or a secret store, not from .zshrc.