Linux and Networking

Linux and Networking

4.4. Functions in bash

First of all we have to take into account what a function is and what it is used for. Imagine that you have to do a task with commands repetitively. The first thing you think about is making a script to automate these tasks. True, I would think the same.

 

Imagine now also that you are going to do (in addition to that) other types of repetitive tasks but there are some parts of those tasks that are the same (they are going to be repeated). You have two options, copy and paste that part of the code so that part of the code will be reproduced in many scripts, or better, create a function that can be used by all scripts.

 

Bash functions allow us to group commands and have the advantage that we can check them and verify that they are efficient. If we want to modify something we will only have to modify the function. What’s more, if something fails, the error will also be more localized and easier to correct.

 

Let’s see below an example of hello holita with functions:

 

#!/bin/bash

HELLO=hello #assign hello to the variable HELLO

function hello { #I created the hello function, the square brackets delimit the function

     local HELLO=holita #I create a local variable HELLO that will only work INSIDE the function

     echo $HOLA #show the content of the local variable HELLO that will contain “holita”

}

echo $HELLO #will display the contents of the variable HELLO on the second line

hello #I call the function that will show on the screen hello

echo $HELLO #show again the contents of the variable HELLO of the second line

 

Proposed exercise.

  1. Copy and run the content of the above script. Try it works.
  2. Create a second function with whatever name you want and modify the script to run the second function as well.

 

The Demeter Project