Menu
CoddyTech

Defining Functions

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 11 of 39.

A function is a named group of commands inside a script. You write the commands once, then run them as many times as you need by typing the function's name, the way you run a command.

#!/bin/bash
divider() {
  echo "----------"
}
divider
echo "Monthly report"
divider

The line divider() { starts the definition and } ends it. Bash stores the commands but runs nothing yet. Each line that says divider calls the function, so bash report.sh prints:

----------
Monthly report
----------

Bash runs a script from top to bottom, so define a function above the first line that calls it. A call above the definition prints an error ending in divider: command not found, and the script goes on with the next line.

challenge icon

Challenge

Easy

Write a script that prints a notice between two lines of equals signs, using a function for the line.

  1. Open notice.sh.
  2. Define a function named rule that prints ========== (ten equals signs).
  3. Below the function, call rule, then print Notice: followed by the first argument, then call rule again.
  4. Save the file.

Try it: run bash notice.sh "Shop closed". It prints:

==========
Notice: Shop closed
==========

Then run bash notice.sh "Back at 3": the middle line becomes Notice: Back at 3 and both lines around it stay the same.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground