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"
dividerThe 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
EasyWrite a script that prints a notice between two lines of equals signs, using a function for the line.
- Open
notice.sh. - Define a function named
rulethat prints==========(ten equals signs). - Below the function, call
rule, then printNotice:followed by the first argument, then callruleagain. - 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground