Kolam Ayer MakersLinux Foundations

Bash Functions

Core Idea

A Bash function gives a name to a group of shell commands that run in the current shell.

Use functions when you repeat a command sequence but do not need a separate executable script yet.

Shape

serve() {
  cd "$HOME/public_html"
  python3 -m http.server "$((10000 + $(id -u)))" --bind 127.0.0.1
}

The function name is serve. The body runs when you type serve, and the foreground server keeps running until you press Ctrl-C.

Arguments

Functions receive arguments as $1, $2, and "$@", just like scripts.

page() {
  if [[ "$#" -lt 1 ]]; then
    printf 'usage: page NAME\n' >&2
    return 1
  fi

  micro "$HOME/src/pages/$1.md"
}

Use return inside a function. Use exit only when you want to end the whole shell or script.

Return Status Versus Output

Functions have two different channels:

is_site_source() {
  [[ -f "$HOME/src/pages/index.md" ]]
}

if is_site_source; then
  printf 'source exists\n'
fi

This function prints nothing. Its status is the answer.

Functions Versus Aliases

Aliases are text shortcuts. Functions are small programs.

Alias:

alias gs='git status'

Function:

gacp() {
  git add "$@"
  git commit
  git push
}

Use aliases for fixed abbreviations. Use functions when you need arguments, tests, variables, or several commands.

Course Example

status() {
  systemctl --user status site.service
  journalctl --user -u site.service --no-pager -n 20
}

This turns a repeated service check into one command you can inspect and improve.

Watch Out

Docs Pointers