Functions in Shell Script with some practical examples

Functions in Shell ScriptShell programming provides the feature of functions  just like any other programming  language. This help us develop the program in a modular manner.Using functions in shell script to perform repetitive tasks is an excellent way to create code reuse. Code reuse is an important part of modern object-oriented programming principles.

What are functions in Shell Script?

Functions are  group pieces of code in a more logical way or practice the divine art of recursion.

Why do require functions?

  1. It helps us reuse the  code
  2. Improve readability
  3. Make debugging easier
  4. Display program as a bunch of steps

How to declare the function ?
Declaring a function is just a matter of writing function


exampl_func  ()




How to call the functions in shell script?
Calling a function is just like calling another program, you just write its name.


Different type of Functions in shell script

Function with out parameter



Hello ()


Echo “hello how are you”



exit 0

Function with parameter passing


Count and display the number of files in the specified directory.





Fcount=`ls -l $CDIR | wc –l`

printf “There are $Fcount files in $CDIR. \n”


FCOUNT /export/home/

exit 0

Function with return parameter




# Define your function here

Hello () {

echo “How are you $1 $2”

return “success”



# Invoke your function

Hello Tom Hanks


# Capture value returned by last command


Some useful examples of functions in shell script

Setting the oracle environment

set_Ora_Env ()



export ORACLE_SID=$1

. /usr/local/bin/oraenv


Checking the OS username

Check_OS_Username ()


USER=`id|awk -F'(‘ ‘{print $2}’|awk -F’)’ ‘{print $1}’`

case ${USER} in


: ;;



echo “$PROG: Must be run as user $1”

echo “Usage: $PROG <SID>”

exit 1;;



Checking the number of arguments passed in the scripts

Check_Options ()


if [ $# -ne 1 ]


echo “\n$PROG: Incorrect number of arguments”

echo “Usage: $PROG <SID>”

echo “$PROG: Abort: exit status 1\n”

exit 1



Related articles in Shell scripting

Unix Script Tutorial 1: What is shell and Shell Scripts

The Guide to Shell Scripting: The Basics

The guide to Shell Script: If statement

Unix shell script while ,for loop with examples

sed command in unix with practical examples

Unix  shell function examples