Skip to content
$ lynuxpro
← Bash Scripting

LESSON 6 OF 17 · INTERMEDIATE · 16 MIN

Functions

HOW IT WORKSFunctions: reusable pieces of a script

log "start"maincalls functionslog()prints with timecheck_url()returns 0/1local varsstay insideResult$? or $(func)
1/4

A function groups commands under a name. Define it before you call it, then use it like any command.

log() { echo "[$(date +%T)] $*"; }

As scripts grow past a screen or two, they get hard to read and the same blocks of code appear in several places. Functions fix both problems. A function is a named group of commands that you can call like any other command, with its own arguments and its own exit code. Well-named functions turn a script into something that reads like a checklist.

In simple words

  • Function: a named block of commands you can call many times, like a mini script inside your script.
  • local: keeps a variable inside the function, so it does not clash with the rest of the script.
  • Return value: functions return an exit code (0 to 255). To return data, print it and capture the output.
  • source: loads functions from another file into the current script.

Defining and calling a function

greet() {  echo "Hello, $1"} greet Leelagreet "the platform team"
SHELLbashutf-8 · 6L
  • Define a function with name() { commands; }. The function name { … } form also works but is Bash-only; the first form is portable.
  • Define before you call. Bash reads a script top to bottom, so the definition must come first.
  • Call it by name, like a command. No parentheses at the call site.

In the practice terminal you can define it on one line (note the spaces after { and the ; before }):

greet() { echo "Hello, $1"; }greet Leelagreet "the platform team"
SHELLbashutf-8 · 3L
Hello, LeelaHello, the platform team
OUTPUTterminalutf-8 · 2L

Arguments

Inside a function, $1, $2, $# and "$@" refer to the function's arguments, not the script's:

show_args() { echo "got $# argument(s): $*"; echo "first is: $1"; }show_args web prod eu-west-1
SHELLbashutf-8 · 2L
got 3 argument(s): web prod eu-west-1first is: web
OUTPUTterminalutf-8 · 2L

$0 stays the script name. Give arguments readable names at the top of the function:

deploy() {  local app=$1 env=$2 version=${3:-latest}  echo "Deploying $app:$version to $env"}
SHELLbashutf-8 · 4L

local: keep variables inside

By default, every variable in Bash is global, even when it is set inside a function. That causes nasty bugs in longer scripts:

name=globalset_name() { name=changed; }set_nameecho "$name"
SHELLbashutf-8 · 4L
changed
OUTPUTterminalutf-8 · 1L

The function silently overwrote the script's variable. Declare function variables with local:

name=globalset_name() { local name=inside; echo "inside: $name"; }set_nameecho "outside: $name"
SHELLbashutf-8 · 4L
inside: insideoutside: global
OUTPUTterminalutf-8 · 2L

Rule: every variable you create in a function should be local, unless you deliberately want to change a global.

Return values: exit codes

return N ends a function with exit code N (0–255), just like exit ends a script. That makes functions work naturally with if, && and ||:

is_known_host() { grep -q "$1" /etc/hosts; }if is_known_host web1; then echo "web1 known"; fiis_known_host mysql || echo "mysql not in hosts"
SHELLbashutf-8 · 3L
web1 knownmysql not in hosts
OUTPUTterminalutf-8 · 2L

Without an explicit return, a function returns the exit code of its last command, which here is grep -q. Explicit codes help when there are several outcomes:

check_disk() {  local usage=$1  if (( usage >= 95 )); then return 2     # critical  elif (( usage >= 85 )); then return 1   # warning  fi  return 0                                # fine}
SHELLbashutf-8 · 7L

Return values: output

return can only give a number. To give back text, have the function print it and capture it with $( ):

get_ip() { awk -v h="$1" '$2 == h {print $1}' /etc/hosts; }ip=$(get_ip web2)echo "web2 is at $ip"
SHELLbashutf-8 · 3L
web2 is at 10.0.1.11
OUTPUTterminalutf-8 · 1L

This is the standard pattern. It means a function that returns text must not print anything else to stdout; send log messages to stderr with >&2 so they are not captured by accident:

get_version() { echo "looking up version..." >&2; echo "2.4.1"; }v=$(get_version)echo "version=$v"
SHELLbashutf-8 · 3L
looking up version...version=2.4.1
OUTPUTterminalutf-8 · 2L

A logging helper

Almost every real script starts with a few small helpers. A logger is the most common:

log() { echo "[$(date +%H:%M:%S)] $*" >&2; }die() { log "ERROR: $*"; exit 1; }log "starting backup"
SHELLbashutf-8 · 3L
[09:42:01] starting backup
OUTPUTterminalutf-8 · 1L

With die, error handling becomes one readable line:

[[ -d $src ]] || die "source folder $src does not exist"cd "$dest" || die "cannot enter $dest"
SHELLbashutf-8 · 2L

The main function pattern

Larger scripts put the top-level logic in a function called main and call it on the last line with all the script's arguments:

#!/usr/bin/env bashset -euo pipefail log() { echo "[$(date +%T)] $*" >&2; }die() { log "ERROR: $*"; exit 1; } usage() {  echo "usage: $0 APP ENV" >&2  exit 2} deploy() {  local app=$1 env=$2  log "deploying $app to $env"  # … real work here …} main() {  [[ $# -eq 2 ]] || usage  deploy "$1" "$2"  log "done"} main "$@"
SHELLbashutf-8 · 24L

Why this helps:

  • The script reads top-down: helpers, then the steps, then main as the table of contents.
  • All functions are defined before any run, so their order does not matter.
  • Variables inside main can be local too.
  • If the file is cut off while downloading (curl … | bash), nothing runs until the last line arrives.

Sourcing functions from a library

Functions you use in many scripts can live in one file that each script sources:

printf 'log() { echo "[lib] $*"; }\nis_prod() { [[ $1 == prod ]]; }\n' > lib.shsource ./lib.shlog "loaded"is_prod prod && log "this is production"
SHELLbashutf-8 · 4L
[lib] loaded[lib] this is production
OUTPUTterminalutf-8 · 2L

source runs the file in the current shell, so its functions become available. You will build a proper library layout in the final lesson.

Real-world scenario: health checks as functions

An SRE writes a check script where each check is a function that returns 0 or 1. The main loop runs them all and counts failures:

check_disk()   { (( $(df --output=pcent / | tail -1 | tr -dc 0-9) < 85 )); }check_nginx()  { systemctl is-active --quiet nginx; }check_api()    { curl -fsS http://localhost:8080/health > /dev/null; } failed=0for check in check_disk check_nginx check_api; do  if "$check"; then    echo "PASS  $check"  else    echo "FAIL  $check"    failed=$((failed + 1))  fidoneexit "$failed"
SHELLbashutf-8 · 14L

Adding a new check is now one line, and the loop treats every check the same way. The exit code tells CI or a monitoring agent how many checks failed.

Common mistakes

  • Calling before defining: command not found.
  • Forgetting local: functions overwrite globals with the same name.
  • return "some text": return only takes a number. Echo text and capture it.
  • Printing logs to stdout in a function whose output is captured: the logs end up inside your variable.
  • Missing ; or spaces in one-line functions: f() {echo hi} fails; write f() { echo hi; }.
  • Naming a function after a command like ls or test: it silently replaces the command for the rest of the script.

Practice

  1. Write square() that prints the square of its argument, and use it as $(square 7).
  2. Write is_even() that returns 0 for even numbers and 1 for odd, and use it in an if.
  3. Write count_errors() that takes a log file path and prints how many lines contain ERROR. Test it on /var/log/app/app.log.
  4. Demonstrate the local bug: set a global i=100, write a function that loops with for i in 1 2 3 without local, call it, and print $i. Then fix it.

Cheat sheet

name() { cmd; cmd; }       define (before use)name arg1 arg2             call$1 $2 $# "$@"              function argumentslocal var=value            variable visible only insidereturn N                   exit code 0–255result=$(name args)        capture printed outputecho "log" >&2             log without polluting outputdie() { echo "$*" >&2; exit 1; }main() { …; }; main "$@"   structure larger scriptssource ./lib.sh            load functions from a file
OUTPUTterminalutf-8 · 10L

Key takeaways

  • Functions are named groups of commands, called like any command, defined before use.
  • They receive their own $1, $2, "$@".
  • Use local for every variable inside a function.
  • return gives an exit code for if and &&; echo text and capture it with $( ) to return data.
  • log, die and a main function make even long scripts easy to read.