As in many programming languages, also in the bash scripts it's possible to create functions that can repeat many times code blocks. The syntax for creating these functions is:
function name()
{
function_code
}
or
function function_name()
{
function_code
}
As you can note, the
function word is optional.
Also the brackets at the end of the function name is optional; indeed, differently from many other programming languages, in the bash scripts all the variables have a global scope. Here is an example:
#!/bin/bash
# This script shows that all the variables are global.
# The program prints out "Function", and not "Main program",
# as it usually happens in C programming language.
function change_variable
{
variable="Function"
}
# Main
variable="Main program"
change_variable
echo "Variable was last modified by: $variable"
To make the variable local, that is to avoid that a variable value is modified in the main program, you can use the command
local. Looking back at the previous example:
#!/bin/bash
# This script shows how to make local a variable inside a function
# The program prints "Main Program" and not "Function, as it happens
# usually in bash scripting, where variables in functions and main
# program are global unless differently specified.
function change_variable
{
local variable="Function"
}
# Main
variable="Main program"
change_variable
echo "Variable was last modified by: $variable"
You can also pass variables to a function by command line parameters, as the following example shows:
#!/bin/bash
# In this example the values 2 and 4 are passed to
# the function through the command line parameters.
function my_function
{
var1=$1
var2=$2
echo "Passed values: $var1 e $var2"
}
my_function 2 4