Functions
Package reusable steps as functions with arguments, local variables, return statuses and output.
- 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.)
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'"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 0means success,return 1(up to 255) failure. With noreturn, a function returns the status of its last command - so a function whose last line is a test is a ready-made predicate forif.
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 decksCargo 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:
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)"5! = 120
Key takeaways
Define with
name() { ...; }and call like a command; inside,$1and"$@"are the call’s arguments.Use
localfor every variable a function owns.Return data by printing it (
result=$(fn)), and success or failure withreturn.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.
The banner function
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
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.
Prime number predicate
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
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…