Functions

Syntax

Definition

function_name() {
    command
}

Invocation

function_name [parameters]

Discussion

  • command may be a single command or multiple commands, which are either placed on different lines or divided by ; on the same line. It’s good practice to indent the commands. And we advise to use spaces rather than tabs to indent lines.
  • We advise to always quote the parameters passed to a function.
  • An alternate syntax is possible:
    function function_name() {
        command
    }
    When the alternate syntax with the reserved word function is used, then the brackets () after the function_name can be omitted.

Example

#!/usr/bin/env bash

abort() {
  echo "Error: ${1}"
  exit 1
}

if (( $# == 0 )); then
  abort "No parameter passed."
else
  echo "Passed parameter: '${1}'"
fi

2022-01-16