Basic functions in Bash

Introduction au scripting Bash

Alex Scriven

Data Scientist

Why functions?

 

If you have used functions in R or Python then you are familiar with these advantages:

  1. Functions are reusable
  2. Functions allow neat, compartmentalized (modular) code
  3. Functions aid sharing code (you only need to know inputs and outputs to use!)
Introduction au scripting Bash

Bash function anatomy

Let's break down the function syntax:

  • Start by naming the function. This is used to call it later.
    • Make sure it is sensible!
  • Add open and close parentheses after the function name
  • Add the code inside curly brackets. You can use anything you have learned so far (loops, IF, shell-within-a-shell etc)!
  • Optionally return something (beware! This is not as it seems)

 

A Bash function has the following syntax:

function_name () {
    #function_code
    return #something
}
Introduction au scripting Bash

Alternate Bash function structure

You can also create a function like so:

function function_name {
    #function_code
    return #something
}

The main differences:

  • Use the word function to denote starting a function build
  • You can drop the parenthesis on the opening line if you like, though many people keep them by convention
Introduction au scripting Bash

Calling a Bash function

Calling a Bash function is simply writing the name:

function print_hello () {
    echo "Hello world!"
}

print_hello # here we call the function
Hello world!
Introduction au scripting Bash

Fahrenheit to Celsius Bash function

Let's write a function to convert Fahrenheit to Celsius like you did in a previous lesson, using a static variable.

temp_f=30

function convert_temp () {
temp_c=$(echo "scale=2; ($temp_f - 32) * 5 / 9" | bc)
echo $temp_c }
convert_temp # call the function
-1.11
Introduction au scripting Bash

Let's practice!

Introduction au scripting Bash

Preparing Video For Download...