Shell Functions  «Prev  Next»
Lesson 4 Calling a function
Objective Invoke a function within a script.

Invoke function within Shell Script

You have seen how to define a function, which copies the function name and instructions into memory. To run the instructions, type the function name in without the opening and closing parentheses. This is known as calling the function. The line of code that calls the function is referred to as a function call. You cannot call a function until after it is defined. In a typical script, you’ll find function definitions at the top and functions calls and other code at the bottom. The code and function calls at the bottom of the script are called the main program. The MouseOver below shows a shell script containing a function definition and a function call.

Write a Unix shell script containing a function definition and a function call

Here is an example of a Unix shell script that defines a function named "greet" and calls it:

function greet {
  echo "Hello, World!"

When you run this script, it will print "Hello, World!" to the console.
> #! /bin/sh sort_file () { 
echo “Enter the name of the file you wish to sort: \c“ 
  read $filename echo
  “Enter the column number you wish to sort on: \c“ 
  read $col sort –t: +$col $filename 
# Main Program starts here echo
“This script allows you to sort a file by a selected column” 
sort_file echo “---------------“ 
	echo “
	End Script” 
<end graphic> 

sort_file (), #This begins the function definition.

}  #This ends the function definition.
# Main Program starts here, Put a comment at the start of the main program. #This will help you locate this section of your script quickly.
sort_file # This is the function call. 
# The only difference between this line and the beginning of the function definition is the opening and closing parentheses. The next lesson shows an example of a script that uses multiple functions.