Functions, arguments and scope

Beginner · 10 min

Name a block of commands with a function, pass it arguments with $1 and $@, return a status or output, and keep variables inside with local.

Before thisExit status and && / || listsLoops - for, while and untilCase statementsWord splitting and the order of expansion

Learn Linux TV · 10 min

Functions, arguments and scope

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Learn Linux TVReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A function is a named block of commands. You define it with `name() { ...; }` and call it like any command, with arguments in `$1`, `$2`, `$@` and `$#`.
  • A function can only `return` a status from 0 to 255. To hand back text or numbers, `echo` them and capture the result with `$(...)`.
  • Variables are global by default, even inside a function. Declare working variables with `local` so they don't leak into the caller.
  • Bash scope is dynamic, so a function can see the `local` variables of whichever function called it.
  • `local v=$(cmd)` hides the command's failure, because `local` itself succeeds. Declare first, then assign on the next line.

Naming a block so you can reuse it

Once a script passes about thirty lines, two things go wrong. The same few commands appear in more than one place, and the main flow gets hard to read. A function fixes both. It gives a block of commands a name, and the name then works like any other command. Think of it as a tiny script that lives inside your script and shares its shell.

Here is logsum version 5. The counting and error handling moved into named pieces, and the last four lines read like a summary of what the script does.

#!/usr/bin/env bash
# logsum v5: the work moves into functions
die() {
  echo "logsum: $*" >&2
  exit 2
}

count_status() {
  local log=$1 pattern=$2
  awk -v p="$pattern" '$8 ~ p' "$log" | wc -l | tr -d ' '
}

report() {
  local log=$1
  [[ -r $log ]] || die "cannot read $log"
  local ok errors
  ok=$(count_status "$log" '^2')
  errors=$(count_status "$log" '^5')
  echo "$log: ok=$ok errors=$errors"
}

for f in "${@:-logs/access.log}"; do
  report "$f"
done

ShellCheck reported nothing. Note the tr -d ' ', which strips the padding from BSD wc.

$ ./logsum logs/access.log nosuch.log; echo "status: $?"
logs/access.log: ok=104 errors=24
logsum: cannot read nosuch.log
status: 2

Arguments

Inside a function, $1, $2 and the rest are the function’s own arguments, not the script’s. $# is the count, and "$@" is every argument, each one kept whole, exactly as for a script.

$ show() { echo "args=$# first=$1 all=[$*]"; printf '<%s>\n' "$@"; }
$ show "a b" c
args=2 first=a b all=[a b c]
<a b>
<c>

Quoting the first argument at the call site kept a b as one item. The local log=$1 line at the top of a function is a habit worth copying. It gives the argument a name, so the body reads clearly.

Return a status, print a value

This catches people coming from other languages. return can only carry an exit status from 0 to 255, for the caller to test with if or &&. A number bigger than that wraps around:

$ big() { return 300; }; big; echo "return 300 -> $?"
return 300 -> 44

To give back data, print it, and let the caller capture the output with command substitution:

$ add() { echo $(( $1 + $2 )); }
$ sum=$(add 2 3); echo "sum=$sum"
sum=5
$ check() { [[ $1 -gt 10 ]]; }
$ check 5; echo "check 5 -> $?"; check 50; echo "check 50 -> $?"
check 5 -> 1
check 50 -> 0

add produces a value, and check produces a yes or no, through the status of its last command. Both patterns are idiomatic. ShellCheck flags the return 300 line as SC2152, “Can only return 0-255. Other data should be written to stdout.”

Scope: global by default

Here is the part that surprises people. In Bash, a variable assigned inside a function is global: it stays after the function ends. The local keyword confines a variable to the function.

$ leaky() { counter=99; hidden=oops; }
$ tidy()  { local counter=50; hidden2=oops; echo "inside tidy: counter=$counter"; }
$ counter=1; leaky; echo "after leaky: counter=$counter hidden=$hidden"
after leaky: counter=99 hidden=oops
$ counter=1; tidy; echo "after tidy: counter=$counter hidden2=$hidden2"
inside tidy: counter=50
after tidy: counter=1 hidden2=oops

leaky overwrote counter, but tidy’s local counter shadowed it and left the original at 1. Notice hidden2 still leaked, because only the variables you declare local are protected.

Bash uses dynamic scope. A function sees the local variables of the function that called it, not only the globals:

$ caller() { local x=outer; callee; }
$ callee() { echo "callee sees x=$x (dynamic scope)"; }
$ caller; echo "x outside: [${x-unset}]"
callee sees x=outer (dynamic scope)
x outside: [unset]

That behaves differently from most languages, where callee wouldn’t see x. In practice it means a missing local in a helper can silently change a caller’s variable, and a typo in a helper’s variable name can read one from far away.

Declaring and assigning together hides failures

One more trap, flagged by ShellCheck as SC2155:

$ f() { local v=$(false); echo "status after local assignment: $?"; }; f
status after local assignment: 0
$ g() { local v; v=$(false); echo "status after separate assignment: $?"; }; g
status after separate assignment: 1

In the first function, local is the last command to run, and it succeeds, so the failure of false vanishes. Splitting declaration and assignment, as in report above, keeps the status. That is why the report function declares local ok errors on one line and assigns them on the next two.

You can see what a function contains with declare -f add, which prints the definition, and type add says add is a function.

About the video

“How To Write Bash Scripts In Linux - Complete Guide (Part 12 - Functions)” from Learn Linux TV is 9 minutes 38 seconds and was uploaded in November 2022. I couldn’t read a transcript. The description says it covers writing and using functions to simplify code and cut repetition. I can’t tell whether it covers local or dynamic scope, so the scope section above stands on my own runs. It is in English. Mental Outlaw’s seven-minute video on local and global variables is linked as a second view: its description includes its source code, which shows variables being global by default and local confining a variable to a function. I found no single video with chapters that covered functions, arguments and scope together, so I kept this pick.

Where this fits

Functions group the work, and the arguments give the script input. The next group begins with turning those arguments into options: getopts.

Check yourself

  1. 01A function sets `total=5` without `local`. Is `total` visible after the call?

    Yes. Variables in Bash functions are global unless declared `local`, so the assignment changes the caller's variable. I saw this with `counter` becoming 99.

  2. 02How does a function give back the text `42` to its caller?

    It prints it with `echo`, and the caller captures it with `result=$(myfunc)`. `return` only carries an exit status from 0 to 255.

  3. 03What does `return 300` do?

    The status wraps modulo 256, so the caller sees 44. ShellCheck reports it as SC2152. Return small status codes and print everything else.

  4. 04Why is `local v=$(false)` followed by `echo $?` misleading?

    `$?` shows the status of `local`, which is 0, not the failing command inside the substitution. Write `local v` first and `v=$(false)` on a separate line.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark