Create a simple bash function

A basic function

The synthaxe to define a function is :

#!/bin/bash
# Basic function
my_function () {
echo Text displayed by my_function
}

#once defined, you can use it like so :
my_function

and it should return

user@bash : ./my_function.sh
Text displayed by my_function

Function with arguments

When used, the arguments are specified directly after the function name. Whithin the function they are accessible this the $ symbol followed by the number of the arguement.

Hence $1 will take the value of the first arguement, $2 will take the value of the second arguement and so on.

#!/bin/bash
# Passing arguments to a function
say_hello () {
echo Hello $1
}
say_hello Guillaume

and it should return

user@bash : ./function_arguements.sh
Hello Guillaume

Overriding Commands

Using the previous example, let's override the echo function in order to make it say hello. To do so, you just need to name the function with the same name as the command you want to replace. When you are calling the original function, make sure you are using the builtin keyword

#!/bin/bash
# Overriding a function
echo () {
builtin echo Hello $1
}
echo Guillaume
user@bash : ./function_arguements.sh
Hello Guillaume

Returning values

Use the keyword return to send back a value to the main program. The returned value will be stored in the $? variable

#!/bin/bash
# Retruning a value 
secret_number () {
return 126
}
secret_number
echo The secret number is $?

This code should return

user@bash : ./retrun_value.sh
The secret number is 126