Creating a Library
It's easy to see how functions can help save typing in a single script, but what if you just happen to use the same single code block between scripts? It's obviously challenging if you have to define the same function in each script, only to use it one time in each script.
There's a solution for that problem! The bash shell allows you to create a library file for your functions and then reference that single library file in as many scripts as you need to.
The first step in the process is to create a common library file that contains the functions you need in your scripts. Here's a simple library file called myfuncs
that defines three simple functions:
$ cat myfuncs
# my script functions
function addem {
echo $[ $1 + $2 ]
}
function multem {
echo $[ $1 * $2 ]
}
function divem {
if [ $2 -ne 0 ]
then
echo $[ $1 / $2 ]
else
echo -1
fi
}
$
The next step is to include the myfuncs
library file in your script files that want...