1. Basic functions in Bash
Let's now learn how to build basic functions in Bash scripts.
2. Why functions?
Functions are a core part of most programming languages. If you have used them in R or Python you will know some of these advantages.
Firstly, functions allow a reusable section of code that reduces repetition.
Therefore you can make neat, compartmentalized code. That is, the code is modular so you can work on, add or subtract different sections as needed.
Finally, functions allow for easy sharing of code. If you know what the function's purpose, the inputs and outputs are then you can use it.
3. Bash function anatomy
A Bash function has the following syntax.
Let's break down the code you see now.
You start by writing a name for your function. Make sure it is a sensible name that makes sense. This enhances code readability.
Add open and closed parentheses after the function name.
Then add curly brackets (or braces). Inside here place the code to run when the function is called. You can use anything you learned so far such as loops, IF statements, calling shell-within-a-shell constructs and more.
You can optionally return something. Beware this is not similar to return values in other languages. We will cover this in the next lesson.
4. Alternate Bash function structure
There is an alternate way you can write functions in Bash, like so.
It is very similar. Can you see the main differences?
Firstly you use the word 'function' before the function name to denote starting a function construction.
Secondly, you don't need parenthesis on the first line. Though you can keep them if you like!
5. Calling a Bash function
To call the function, simply write the name you set when building it.
Here is a simple function to print some text.
We then call it by using the same name.
As expected, it prints out the words.
6. Fahrenheit to Celsius Bash function
Let's practice by writing a function to convert Fahrenheit to Celsius, just like you did in a previous lesson.
We have a static variable 'temp_f' which is the temperature we want to convert and will be used inside the function.
We will use the 'function-word' method to create the function and call it 'convert_temp'.
Inside we create a variable, 'temp_c' by calling a shell-within-a-shell to implement the arithmetic to convert the temperature. Take a second to dissect this if you like - it should be familiar from previous lessons, just compressed a bit.
Then we simply print it out the converted temperature and close the function.
Below, we call the function.
As expected, 30 in Fahrenheit is -1.11 in Celsius.
7. Let's practice!
Let's practice creating some basic functions in Bash!