Functions
Most (all?) shells have the means of creating new “internal” commands. This
is done by creating shell
functions. Shell functions are just like those
in a programming language. Sets of commands are grouped together and jointly
called by a single name.
The format for functions is:
function_name()
{
first thing to do
second thing to do
third thing to do
}
Functions can be defined anywhere, including from the command line.
All you need to do is simply type in the lines one at a time, similar to the way shown
above. The thing to bear in mind is that if you type a function from a command
line, once you exit that shell, the function is gone.
Most of the time functions are defined within a shell script. As you might expect,
the function is only valid within the scope of the scipt. However, if you
source the shell scripts as we discussed in
the section on shell basics,
then the function is valid for the current shell.
You can also pass arguments to shell functions, just like commands. A
simple example is a script that looks like this:
display()
{
echo $1
}
display Hello
The output would be
Hello
Here we need to be careful. The variable
$1 is the positional parameter from the call to the display function and not to
any script containing this function. We can see how this works if we
create a the script to look like this:
display()
{
echo $1
}
display $1
echo $1
This is slightly different than the function by itself in that we first call the function
itself and then there is an extra
echo at the end. Lets call the script display.sh, change the
permissions so that it is executable and start it like this:
display.sh Hi
The output would then look like this:
Hi
Hello
The first echo shows us the parameter from the function and the second
one shows us the parameter from the command line.
As you can see, although we are using the same positional parameter ($1), what is assigned to
it depends on the scope. The parameter command line passed on the command
line (“Hi”) is valid for the entires scope of the script. However, it is overwritten within
the scope of the function by the new value.