Um momento
0xD0Lesson 14 of 18

Functions

Package reusable steps as functions with arguments, local variables, return statuses and output.

24 min 7-question quiz 2 code exercises
By the end of this lesson you can
  • Define and call functions that take arguments
  • Keep variables private with local
  • Return data through output and success or failure through return

A function is a named group of commands that you call like any other command. It gets its own $1, $2, $# and "$@" - the arguments of that call, not the script’s:

1greet() {
2  echo "Welcome aboard, $1!"
3}
4greet Ada            # Welcome aboard, Ada!

Define functions before you call them. (function greet { ... } also works; greet() { ... } is the portable style.)

local.sh
1status="nominal"
2check_deck() {
3  local deck=$1          # local: exists only during this call
4  status="checked $deck"  # no local: overwrites the global!
5  echo "inspecting $deck ($# argument)"
6}
7check_deck 7
8echo "deck is '${deck:-}' and status is '$status'"
Output
inspecting 7 (1 argument)
deck is '' and status is 'checked 7'

Two ways to give something back

Functions can’t return strings the way they do in other languages. Instead:

  • Output is the data. Print the result and let the caller capture it: area=$(rectangle_area 4 5).
  • Status is the verdict. return 0 means success, return 1 (up to 255) failure. With no return, a function returns the status of its last command - so a function whose last line is a test is a ready-made predicate for if.
returns.sh
1rectangle_area() {
2  echo $(( $1 * $2 ))
3}
4is_number() {
5  [[ $1 =~ ^[0-9]+$ ]]      # the test's status becomes the function's
6}
7shout() {
8  local text="$*"
9  echo "${text^^}!"
10}
11area=$(rectangle_area 4 5)
12echo "Cargo bay floor: $area m2"
13for value in 42 forty-two; do
14  if is_number "$value"; then echo "$value is a number"; else echo "$value is not"; fi
15done
16shout "red alert" all decks
Output
Cargo bay floor: 20 m2
42 is a number
forty-two is not
RED ALERT ALL DECKS!

As scripts grow, move shared functions into a file and load it with source lib.sh (or its shorthand . lib.sh). Sourcing runs the file in the current shell, so its functions and variables become available - the same mechanism that loads your ~/.bashrc.

Functions can call themselves, too. Recursion is rarely the right tool in Bash, but it works:

recursion.sh
1factorial() {
2  local n=$1
3  if (( n <= 1 )); then echo 1; return; fi
4  echo $(( n * $(factorial $(( n - 1 ))) ))
5}
6echo "5! = $(factorial 5)"
Output
5! = 120

Key takeaways

  • Define with name() { ...; } and call like a command; inside, $1 and "$@" are the call’s arguments.

  • Use local for every variable a function owns.

  • Return data by printing it (result=$(fn)), and success or failure with return.

  • A function ending in a test works as a predicate: if is_number "$x"; then.

Lesson quiz

7 questions · pass with 5 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write Bash scripts

Write a script in the editor and run it for real against sample input. Each run gets a fresh Linux sandbox with Bash 5.2 and the GNU tools on Wandbox, a free public service - so experiment freely, even with rm. Your script and test input are sent there.

Exercise 1

The banner function

+25 XP

Write a function banner that prints its argument inside a box of = signs. The bars are 4 characters longer than the text:

===========
| Kestrel |
===========

The starter reads each line of stdin and calls banner on it.

  • Kestrel
  • Two banners
script.sh
Loading editor…

Your script runs with Bash 5.2 and GNU tools on Wandbox, a free public service, in a fresh sandbox each time. Your script and test input are sent to that service.

Exercise 2

Prime number predicate

+25 XP

Write a function is_prime that succeeds (status 0) when its argument is a prime number and fails otherwise - it should print nothing. For each number on stdin, print N is prime or N is not prime using if is_prime "$n". Remember 0 and 1 are not prime.

  • Small numbers
  • Bigger numbers
script.sh
Loading editor…

Your script runs with Bash 5.2 and GNU tools on Wandbox, a free public service, in a fresh sandbox each time. Your script and test input are sent to that service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: