Shell Programming - Functions

Unix

In this tutorial we will learn about functions in Shell Programming.

What is a function?

A function is a block of code written for a specific task.

For example, a simple interest function will have code to compute the simple interest based on some input data.

Functions in Shell are similar to subroutines or procedures in other programming language like C.

Function syntax

Following is the syntax of a function.

function functionName()
{
  # some code goes here...
}

Where functionName is the name of the function. After the name we have the opening and closing parenthesis ().

The body of the function starts from { and ends at }.

Inside the opening and closing curly brackets {} we have the body of the function.

Another way of creating a function is given below.

functionName()
{
  # body of the function
}

Function name

We follow the given rules when naming functions.

  • Name must start with letters (a-z or A-Z) or underscore _
  • After that we can use letters (a-z and A-Z), underscore _ and digits (0-9)
  • Don't put space in the function name
  • Don't use special keywords like echo, printf etc to name your function

Example #01: Write a Shell Script to print "Hello World" using function

In the following example we are creating greetings function.

#!/bin/sh

# create a function
function greetings()
{
  echo "Hello World"
}

# call the function
greetings

Output:

$ sh example01.sh 
Hello World

Passing argument to a function

We can also pass arguments to a function in shell script and access them using variables like $1, $2, $3... where, $1 points at the first argument, $2 points at the second argument and so on.

Example #02: Write a Shell Script to create a function that accepts user name and displays a greetings message

In the following example we are creating greetings function which accepts an argument and prints a greetings message.

#!/bin/sh

# create a function
greetings() {
  echo "Hello $1"
}

# call the function
greetings "Yusuf Shakeel"

Output:

$ sh example02.sh 
Hello Yusuf Shakeel

Example #03: Write a Shell Script to print greetings message using the name entered by the user

In this example we will first take the name from the user and save it in variable name.

#!/bin/sh

# function
greetings() {
  echo "Hello $1"
}

# take user name
printf "Enter your name: "
read name

# call the function
greetings "$name"

Output:

$ sh example03.sh 
Enter your name: Yusuf Shakeel
Hello Yusuf Shakeel

Return Code

We use the return command to return value from a function.

Example #04: Write a Shell Script to create a function that takes a number as argument and finds the square. On success it returns 0 otherwise, 1

For this we will create square function which will take a number as argument.

#!/bin/sh

# function
square() {

  # if argument missing
  if [ -z "$1" ]
  then
    return 1  # return error code
  fi
  
  # assign argument to variable n
  n="$1"

  # find square
  result=`expr "$n * $n" | bc -l`

  return 0    # return success code
}

# take user input
printf "Enter a number: "
read num

# call the function
square "$num"

# save the returned code from the above function call
returnCode=$?

if [ $returnCode -eq 0 ]
then
  # display the result
  printf "Square of %d = %d\n" "$num" "$result"
elif [ $returnCode -eq 1 ]
then
  printf "Error Code: $returnCode Error: Number missing!\n"
else
  printf "Error Code: $returnCode Error: Unknown!\n"
fi

Output:

$ sh example04.sh 
Enter a number: 5
Square of 5 = 25


$ sh example04.sh 
Enter a number: 
Error Code: 1 Error: Number missing!

Value returned by the function is accessed using $? so, we use it to save the returned value in variable $returnCode.

Note! The variable result inside the square function is accessible from outside the function inside the script file.

So, result variable is like a global variable even though it is inside the square function. This is different from what we know from other programming languages like C, C++, Java etc. were a variable defined inside a function can't be accessed from outside directly.

Example #05: Write a Shell Script to compute Simple Interest based on user input

#!/bin/sh

# simple interest function
simpleInterest () {
  p="$1"
  r="$2"
  t="$3"
  si=`expr "($p * $r * $t)/100" | bc -l`
}

# take user input
printf "Enter Principal: "
read pr

printf "Enter Rate [0-100]: "
read rt

printf "Enter Time [in years]: "
read tm

# call function
simpleInterest $pr $rt $tm

printf "Simple Interest: %.3f\n" "$si"

Output:

$ sh example05.sh 
Enter Principal: 100
Enter Rate [0-100]: 10
Enter Time [in years]: 2
Simple Interest: 20.000