UNIX‎ > ‎

Shell scripts Functions

What is Function ?

Function is a series of commands which performs particular activity in the script.

Uses of Functions ?

  1.   Code Reusability
  2.   Complexity of the script can be divided into smaller sections
  3.    Writing functions in the script will reduce the time

Syntax of Function:


  Function name ()

 {

         Commands

}


Example1:

Write a script to print the "hello world" by using Function ?

#!/bin/bash
#script for priniting Hello world
Hello ()
{
echo "Hello World"
}
 Hello


Output:
[vagrant@jhrk functions]$ sh basicfunexa1.sh
Hello World



Example2:

script for listing files with given extension ?


#! /bin/bash

#script for listing  files with given extension

lsext ()

{

find -type -f -iname '*.' ${1} ' ' -exec ls -l {}   \; ;

}


Output:



Example 3:

Script to execute a given Linux command on a group of files

 






Passing Parameters to Function

example 1:




Output:


Nested Functions

Nested Functions are the functions which can call themselves and other functions. A function which call itself is  known as recursive function .

Syntax:

fun1 ()
{
commands
fun2  ()
{
commands
}
}


Example:





Output:


Function return value

You cannot return an arbitrary result from a shell function. You can only return a status code which is an integer between 0 and 255. (While you can pass a larger value to return, it is truncated modulo 256.) The value must be 0 to indicate success and a different value to indicate failure; by convention you should stick to error codes between 1 and 125, as higher values have a special meaning (bad external command for 126 and 127, killed by a signal for higher values).
#!/bin/bash
# This script will illustrate the use of return statement
# It takes command line arguments as your name
#

choice() {
  echo "Is your name $* ?"
  while true
  do
    echo -n "Enter yes or no:"
    read x
    case "$x" in
      y | yes ) return 0;;
      n | no ) return 1;;
      * ) echo "Answer yes or no"
    esac
  done
}

# main begins here...

echo "Original parameters are $*"
if choice "$1"
then
  echo "Hi $1, nice name"
else
  echo "Never mind"
fi

The execution of the above script as follows
Shell scripting Function return value

Screenshot... Hari
:
Comments