Shell Scripting – Functions [Part2]

This post is a followup on the first article – basics of Shell scripting [herenote: increasing the scope beyond Performance Engineers only].

In this write up we look at how to modularize a shell script using Functions and how to create a set of useful functions -> convert them in to library -> use them across scripts.

Functions:

It is a good practice to write shell scripts as functions rather than stand alone scripts so that they can be easily incorporated in to other scripts without incurring the overhead of system calls. While there is no import feature like in Python, there are capabilities of Sourcing files is shell scripts.
But first, lets look at ways of writing functions and invoking them.

Below are the ways of defining a function in shell script (library.sh), where all 3 – hello1, hello2 and hello3 are valid functions.

#!/bin/bash

function hello1() {
        echo "Hello from 1"
}
function hello2 {
        echo "Hello from 2"
}
hello3() {
        echo "Hello from 3"
}

As you can see above :
– the keyword function is optional
– the brackets along with function name are optional as well.

Usually, I write all the required functions like above and create a library.sh file out of it. Then source this file in all the other shell scripts, so that all the functions are readily available for use.

#!/bin/bash

source library.sh

#below: invoking the functions from above library.sh file
hello1
hello2
hello3

There are instances when you want to return a value from a function, save it to a variable and use it further. Although return keyword for a function only returns the exit code of the function, you can always echo the output that you want to return and catch in a variable. Example shown below.
Further reading on exit code in shell scripts – link
For the ease of showing the code, I am calling the function from within the script in below code.

#!/bin/bash

#addition function adds the values and returns the result via "echo"
function addition() {
        add=$(($1+$2))
        echo $add
}

#save the output of function to "result" variable
result=$(addition 2 3)
echo $result

Above example shows :
– how to call a function with parameters — “addition 2 3
– how to return the value from a fucntion — “echo $add
– how to store the output from a function for later use — “result=$(addition 2 3)

Side note : To debug a shell script, either use “set -x” at the beginning of the script or run the script with “-x” parameter.
Details here – link

Bottom-line : You can write modern modular code with shell script using functions and source it across in multiple scripts.

Leave a comment