Shell Functions

The shell allows you to define functions. A shell function is loaded when the shell sees the definition. However, the text of the function is not executed at the time the function is loaded. Instead, a shell function is called like a script. Parameters can be passed to the function and used in the function under the names $1, $2, etc.

For example

$ function(){
>   echo My first parameter is $1
>   echo My second parameter is $2
>}
$ function one two
My first parameter is one
My second parameter is two
$

Unlike C, you do not specify parameters inside the (). The () syntax just informs the shell that this is a function definition.

If a shell function is used inside a script, the values of $1, $2, etc in the function refer to the function's parameters and not the script's parameters. They are local to the function. Any other shell variable introduced or used in a function, however, is global. The shell does not really support local variables within functions.

Many scripts consist of several functions together with a small main body. Remember that shell functions are not executed when they are loaded. For example

Initialize(){
  #...
  #...
}

Print_Message(){
  #...
  #...
}

Do_Work(){
  #...
  #...
}

Clean_Up(){
  #...
  #...
}

Initialize
Print_Message "Hello There"
Do_Work
Clean_Up

You can use shell functions to simulate aliases or commands from other operating systems.

cls(){
  echo "\033[2J"
}

dir(){
  ls -l $1
}

copy(){
  cp $1 $2
}

sendall(){
  mail `cat mailing.list` < $1
}

If you load these functions in your .profile script, they will be available to you whenever you are logged in. Note that although the examples above are simple, there is no limit to the complexity of a shell function. Large functions with many nested control structures are possible and realistic.