Unix Shell Script Functions with Parameters and Return

Overview of Unix Shell Functions:

Shell Functions are used to specify the blocks of commands that may be repeatedly invoked at different stages of execution.

The main advantages of using unix Shell Functions are to reuse the code and to test the code in a modular way.

This tutorial will explain you all about Functions in Unix. 

Unix Video #18:

Working with Functions in Unix

Shell functions typically do not return the result to the calling code. Instead, global variables or output streams are used to communicate the result. The variable ‘errno’ is often used to communicate whether a command ran successfully or not.

A number of commands also print out their result into the ‘stdout’ stream so that the calling function can read into a variable.

In this tutorial we will cover:

  • How to create functions
  • Passing parameters to a function
  • Returning a value from a function

Syntax for defining functions:

function_name()
{
 …
 <statements>
 …
}

To invoke a function, simply use the function name as a command.

Example:

$ function_name

To pass parameters to the function, add space separated arguments like other commands.

Example:

$ function_name $arg1 $arg2 $arg3

The passed parameters can be accessed inside the function using the standard positional variables i.e. $0, $1, $2, $3 etc.

Example:

function_name()
{
 …
 c = $1 + $2
 …
}

Functions can return values using any one of the three methods:

#1) Change the state of a variable or variables.

#2) Use the return command to end the function and return the supplied value to the calling section of the shell script.

Example:

function_name()
{
 echo “hello $1”
 return 1
}

Running the function with a single parameter will echo the value.

$ function_name ram
hello ram

Capturing the return value (stored in $?) as follows:

$ echo $?
1

#3) Capture the output echoed to the stdout.

Example:

$ var = `function_nameram`
$ echo $var
hello ram

Check our upcoming tutorial to know more about Text Processing in Unix.

PREV Tutorial | NEXT Tutorial


Further Reading