Functions

Generally, shell functions are defined in a file and sourced into the environment as follows:

$ . file

They can also be defined from the command line. The syntax is simple:

name () {
commands;
}

Parameters can be passed, and are referred to as $1, $2, and so on. $0 holds the function name, while $# refers to the number of parameters passed. Finally, $* expands to all parameters passed. Since functions affect the current environment, you can do things like this:

tmp () {
cd /tmp
}

This will cd to the /tmp directory. You can define similar functions to cd to directories and save yourself some typing. This can't be done in a shell script, since the shell script is executed in a subshell. That is, it will cd to the directory, but when the subshell exits, you will be right where you started.

Here is a function that uses arguments:

add () {
    echo $[$1 + $2];
}

To use the function:

$ add 2 2
4
$

The following example shows that the notion of arguments is context-dependent inside a function.

#!/bin/bash
#functionArgs.sh

echoargs ()
{
    echo '=== function args'
    for f in $*
    do
        echo $f
    done
} 

echo --- before function is called
for f in $*; do echo $f; done

echoargs a b c

echo --- after function returns
for f in $*; do echo $f; done

Try the above out by creating a script and running it!