Here's a very simple example of a bash function:
- Code: Select all
#!/bin/bash
calculate() {
if [ ! -z $1 ] && [ ! -z $2 ]; then
echo "The result of $1 plus $2 is " $(($1 + $2))
fi
}
calculate $1 $2
exit
The actual function is cacluate, which takes two parameters, tests to make sure they are there, adds them together and outputs the result. The penultimate line simply calls the function using the two parameters passed to the script, but you could just as easily replace it with:
- Code: Select all
calculate 45 9
calculate 2 6
calculate 101 202
and so on, to add up each pair of numbers that you pass to it. Really, all a function is is a mechanism to stop you having to repeat the same codeblock throughout your script. The three calculate lines shown above would expand internally to:
- Code: Select all
if [ ! -z 45 ] && [ ! -z 9 ]; then
echo "The result of 45 plus 9 is " $((45 + 9))
fi
if [ ! -z 2 ] && [ ! -z 6 ]; then
echo "The result of 2 plus 6 is " $((2 + 6))
fi
if [ ! -z 101 ] && [ ! -z 102 ]; then
echo "The result of 101 plus 102 is " $((101 + 102))
fi
so you see how much less typing is required for reusable code blocks by using a function.
Just to add, this really is a very simplistic example and you would be unlikely to use a function to do this, but the real power is for complex code blocks. Think of the code between the curly braces in the function as it's own script within a script,which can be as simple or as complex as necessary, and you get the idea.
EDIT: If you are familiar with BASIC programming, functions are the same as BASIC PROCEDURES.