Functions

  • Functions in bash scripting are a great option to reuse code. 
  • A Bash function can be defined as a set of commands which can be called several times within bash script. 
  • The purpose of function in bash is to help you make your scripts more readable and avoid writing the same code again and again.
  •  It also allows the developers to break a complicated and lengthy code to small parts which can be called whenever required. 
  • Functions can be called anytime and repeatedly, which will enable us to reuse, optimize, and minimize the code.

Note: 
  • To remove the definition of a function from the shell, use the unset command with the .f option. 
  • This command is also used to remove the definition of a variable to the shell.



------------------------------------------------------------------------------------------------------------------------------------
Sample Program
------------------------------------------------------------------------------------------------------------------------------------

[haritaraka12078@cxln4 ~]$ cat>fun1.sh

#!/bin/bash

 #----------------1st method--------------------------------------------------------------------------------
JAVA () {
    echo 'Welcome to Javatpoint.'
}
JAVA

#---------------2nd method---------------------------------------------------------------------------------
function JTP {
    echo 'Welcome to Javatpoint.'
}
JTP


[haritaraka12078@cxln4 functionscripts]$ sh fun1.sh
Welcome to Javatpoint.
Welcome to Javatpoint.



------------------------------------------------------------------------------------------------------------------------------------
Calling function arguments  
------------------------------------------------------------------------------------------------------------------------------------
  • we are required to insert them just after the function's name. 
  • We must apply spaces between function name and arguments. 
  • It will also be a great choice to use double quotes around the arguments to prevent misparsing of the arguments with spaces in it.

Following are some key points about passing arguments to the bash functions:

  • The given arguments are accessed as $1, $2, $3 ... $n, corresponding to the position of the arguments after the function's name.
  • The $0 variable is kept reserved for the function's name.
  • The $# variable is used to hold the number of positional argument/ parameter given to the function.
  • The $* and $@ variables are used to hold all the arguments/ parameters given to the function.
    1. When $* is used with double quotes (i.e., "$*" ), it expands to a single string separated by the space. For example, "$1 $2 $n etc".
    2. When $@ is used with double quotes (i.e., "$@" ), it expands to the separate string. For example, "$1" "$2" "$n" etc.
    3. When $* and $# are not used with the double quotes, they both are the same.


------------------------------------------------------------------------------------------------------------------------------------
Example
------------------------------------------------------------------------------------------------------------------------------------

[haritaraka12078@cxln4 functionscripts]$ cat>fun2.sh
function_arguments()
    {
    echo $1
    echo $2
    echo $3
    echo $4
    echo $5
    }

#Calling function_arguments
function_arguments "We" "welcome" "you" "on" "Javatpoint."


[haritaraka12078@cxln4 functionscripts]$ sh fun2.sh
We
welcome
you
on
Javatpoint.




------------------------------------------------------------------------------------------------------------------------------------
Variable Scope  
------------------------------------------------------------------------------------------------------------------------------------
  • Global variables are defined as the variables which can be accessed anywhere within the script regardless of the scope
  • By default, all the variables are defined as global variables, even if they are declared inside the function.
  • Local variables can be declared within the function body with the ?local? keyword when they are assigned for first time

local var_name=<var_value> 


[haritaraka12078@cxln4 functionscripts]$ cat>fun3.sh

#!/bin/bash

v1='A'
v2='B'

my_var ()
{
local v1='C'
v2='D'
echo "Inside Function"
echo "v1 is $v1."
echo "v2 is $v2."
}

echo "Before Executing the Function my_var"
echo "v1 is $v1."
echo "v2 is $v2."

my_var
echo "After Executing the Function my_var"
echo "v1 is $v1."
echo "v2 is $v2."


[haritaraka12078@cxln4 functionscripts]$ sh fun3.sh
Before Executing the Function my_var
v1 is A.
v2 is B.
Inside Function
v1 is C.
v2 is D.
After Executing the Function my_var
v1 is A.
v2 is D.
 

As per output, 
if we set a local variable within the function body with the same name as an existing global variable, 
then it will have precedence over the global variable. Global variables can be modified within the function.




------------------------------------------------------------------------------------------------------------------------------------
Return Values
------------------------------------------------------------------------------------------------------------------------------------

  • the function has to send the data back to the original calling location.
  • When a bash function completes, its return value is the status of the last executed statement in the function. 
  • It returns 0 for the success status and non-zero decimal number in the 1-255 range for failure.
  • The return status can be indicated by using the 'return' keyword, and it is assigned to the variable $?. 
  • The return statement terminates the function and works as the function's exit status.


[haritaraka12078@cxln4 functionscripts]$ cat>funreturn.sh

#!/bin/bash

#Setting up a return status for a function
print_it () {
    echo Hello $1
    return 5
}
print_it User
print_it Reader
echo The previous function returned a value of $?


#Another better option to return a value from a function is to send the value to stdout using echo or printf commands

echo "#------------------------echo or printf -------------------------------------------------#"

print_returnvalue () {
    local my_greet="Welcome to Javatpoint."
    echo "$my_greet"
}

my_greet="$(print_returnvalue)"
echo $my_greet



[haritaraka12078@cxln4 functionscripts]$ sh funreturn.sh
Hello User
Hello Reader
The previous function returned a value of 5
#------------------------echo or printf -------------------------------------------------#
Welcome to Javatpoint.




------------------------------------------------------------------------------------------------------------------------------------
Overriding Commands
------------------------------------------------------------------------------------------------------------------------------------

We have an option to override the bash commands by creating a function with the same name as the command that we are going to override. 

  • For example, if we want to override the 'echo' command, then we have to create a function with the name 'echo'.


Example

In this example, we have overridden the 'echo' command and added the time stamp in the form of the argument to the 'echo' command.

[haritaraka12078@cxln4 ~]$ cat>funoverride.sh

#!/bin/bash
#Script to override command using function

echo () {
    builtin echo -n `date +"[%m-%d %H:%M:%S]"` ": "
    builtin echo $1
}

echo "Welcome to Javatpoint."


[haritaraka12078@cxln4 ~]$ sh funoverride.sh
[06-15 12:13:33] : Welcome to Javatpoint.




------------------------------------------------------------------------------------------------------------------------------------
BASIC EXAMPLE:1
------------------------------------------------------------------------------------------------------------------------------------

[haritaraka12078@cxln4 functionscripts]$ cat>funexam3.sh

read -p "Enter first number: " num1
read -p "Enter second number: " num2

function add()
{
sum=$(( $num1 + $num2 ))
echo "Sum is: $sum"   
}

function minus()
{
 sub=$(( $num1 - $num2 ))
 echo "minus is: $sub"   
}

function mul()
{
 Multiple=$(( $num1 * $num2 ))
 echo "Multiple is: $Multiple"   
}

add
minus
mul



[haritaraka12078@cxln4 functionscripts]$ sh funexam3.sh
Enter first number: 10
Enter second number: 5
Sum is: 15
minus is: 5
Multiple is: 50



------------------------------------------------------------------------------------------------------------------------------------
BASIC EXAMPLE:2
------------------------------------------------------------------------------------------------------------------------------------

[haritaraka12078@cxln4 functionscripts]$ cat>funexam2.sh

# syntax.sh
# Declaring functions using the reserved word function

# Multiline
function f1 {
echo              
echo -------Multiprogram------------- 
echo Hello I\'m function 1
                echo Bye!
echo      
echo         
}


# One line
function f2 { echo                        ;echo ------Oneline Program-------- ; echo Hello I\'m function 2; echo Bye!;echo                        ;}


# Declaring functions without the function reserved word
# Multiline
f3 () { 
echo              
echo ------functions without the function reserved word -Multiline-------- 
        echo Hello I\'m function 3
        echo Bye!
echo 
}


# One line
f4 () { echo                        ; echo ------functions without the function reserved word -Oneline-------- ; echo Hello I\'m function 4; echo Bye!; echo                        ; }

# Invoking functions
f4
f3
f2
f1



[haritaraka12078@cxln4 functionscripts]$ sh funexam2.sh

------functions without the function reserved word -Oneline--------
Hello I'm function 4
Bye!


------functions without the function reserved word -Multiline--------
Hello I'm function 3
Bye!


------Oneline Program--------
Hello I'm function 2
Bye!


-------Multiprogram-------------
Hello I'm function 1
Bye!



------------------------------------------------------------------------------------------------------------------------------------
BASIC EXAMPLE:3
------------------------------------------------------------------------------------------------------------------------------------

[haritaraka12078@cxln4 functionscripts]$ cat>funexam.sh

#!/bin/sh
# Define your function here

echo "                                   "
echo "                                   "
echo "#-------Example -----Basic Funtion Program --------------------#"
Hello () {
   echo "Hello World"
}
# Invoke your function
Hello
echo "                                   "
echo "                                   "



# Define your function here
echo "#-------Example ----- Pass parameters --------------------#"

Hi () {
   echo "Hello World $1 $2"
}

# Invoke your function
Hi Zara Ali
echo "                                   "
echo "                                   "



# Calling one function from another
echo "#-------Example ----- Calling From one funtion to another funtion --------------------#"

number_one () {
   echo "This is the first function speaking..."
   number_two
}

number_two () {
   echo "This is now the second function speaking..."
}

# Calling function one.
number_one
echo "                                   "
echo "                                   "



[haritaraka12078@cxln4 functionscripts]$ sh funexam.sh


#-------Example -----Basic Funtion Program --------------------#
Hello World


#-------Example ----- Pass parameters --------------------#
Hello World Zara Ali


#-------Example ----- Calling From one funtion to another funtion --------------------#
This is the first function speaking...
This is now the second function speaking...