BASH Programming

How to Create and Utilize Bash Functions

The function is a useful part of any programming language to define the block of code that can be used in multiple types by calling the function. The function declaration and use of the function arguments in the Bash function are not similar to other programming languages. The function keyword is not mandatory to use to define the functions in Bash. Generally, $1, $2, $3…$n variables are used to read the function arguments in Bash. The brackets “()” are also not necessary to call a function in Bash. The methods of creating and using the user-defined Bash functions are shown in this tutorial using multiple examples.

Different Types of Bash Function Arguments

The purposes of the different types of Bash function arguments are explained as follows:

 

Function Argument Purpose
$0 It contains the script name with the location.
$# It counts the total number of arguments.
$@ or $* It contains the positional argument list.
“$@” It extracts a separate string from the list.
“$*” It extracts the list as a string.
$1, $2, …$n These variables are used to read the arguments that are passed after the function names.

 

List of Content:

  1. Define and Call a Function
  2. Define a Function with the Global Variable
  3. Define a Function with the Local Variable
  4. Define a Function with Argument
  5. Define a Function that Returns a Single Value
  6. Define a Function that Returns Multiple Values
  7. Define a Function to Override the Command
  8. Define a Function to Read from a File
  9. Define a Function to Write into a File
  10. Define a Function to Read a Reference Argument

Define and Call a Function

The method of declaring a simple function and calling the function in the Bash script is shown in the following script. The function prints a simple message when it is called.

#!/bin/bash

#The way to declare and call the bash function
#has been shown in this script

#Define a simple function
function testFunc
{
    echo "It is a testing function."
}

#Call the function
testFunc

 

Output:

The following output appears after executing the previous script. The message, “it is a testing function”, is printed after calling the function:

Go to top

Define a Function with the Global Variable

The variables which are declared outside the function are called global variables. These variables are accessible anywhere in the script. The method of reading the global variables inside the Bash function is shown in the following script. Two string values are taken as input from the user. When the function is called from the script if the input values are non-empty, the concatenated values of the input values are printed. Otherwise, an error message is printed.

#!/bin/bash

#Take input from the user
read -p "Enter the first name: " firstname
read -p "Enter the last name: " lastname

#Define a simple function
concat_str
{
     #Check whether the global variables are empty or not
     if [[ ! -z $firstname && ! -z $lastname ]]
     then
        echo "Full Name: $firstname $lastname"
     else
        echo "First name or Last name is empty."
     fi

}

#Call the function
concat_str

 

Output:

The following output appears after executing the script for the input values, “Nila” and “Rahman”:

Go to top

Define a Function with the Local Variable

The variables which are used inside the function are called local variables. Both global and local variables are used in the following script. The function of the script finds out whether the value of the global variable is divisible by 5 or not. Here, the “$number” is the global variable and the “$remainder” is the local variable.

#!/bin/bash

#Define a global variable
number=65

#Define a function
function calculate
{
     #Define a local variable
     local remainder=$(($number%5))

     #Check whether the number is divisible by 5 or not
     if [ $remainder == 0 ]
     then
        echo "$number is divisible by 5."
     else
        echo "$number is not divisible by 5."
     fi
}

#Call the function
Calculate

 

Output:

The following output appears after executing the script. Here, the value of “$number” was 65 which is divisible by 5:

Go to top

Define a Function with Argument

Multiple arguments are passed into the function by separating the arguments with the space after the function name in Bash. The $1, $2, $3, etc. variables are used to read the argument values sequentially. Four numbers are passed as the argument values at the time of calling the function for the first time. Four variables are passed as the argument values at the time of calling the function for the second time. The function returns the sum of all argument values.

#!/bin/bash

addition()
{
    #Read the argument values
    n1=$1
    n2=$2
    n3=$3
    n4=$4
    #Calculate the sum of the arguments
    ((sum=$n1+$n2+$n3+$n4))
    #Print the calculated result
    echo "The sum of $n1, $n2, $n3, and $n4 is $sum"
}

#Call the function with 4 numeric arguments
addition 10 30 20 40

#Take four numbers from the user
read -p "Enter 4 numbers: " num1 num2 num3 num4
#Check the four variables
if [[ ! -z $num1 && ! -z $num2 && ! -z $num3 && ! -z $num4 ]]
then
    addition $num1 $num2 $num3 $num4
else
    echo "Four numbers are not taken."
fi

 

Output:

The following output appears after executing the script. The sum of 10, 30, 20, and 40 is 100 and the sum of 6, 9, 5, and 3 is 23. The correct values are printed in the output:

Go to top

Define a Function that Returns a Single Value

The Bash function can return a single and multiple values. The “return” statement is used to return a numeric value from the Bash function. The “echo” command is used to return a single or multiple values from the function to the caller of the function. In the following script, the function is used to return the multiplication result of two numbers that are taken from the user. The “$?” is used to read the returned value of the function.

#!/bin/bash

#Take two numbers from the user
read -p "Enter the first number: " n1
read -p "Enter the second number: " n2

#Define a function to calculate the multiplication of two numbers
multiply_number ()
{
    #Multiply two numbers
    ((result=n1*n2))
    #Return the result of the multiplication
    return $result
}

#Call the function
multiply_number
#Print the returned value
echo "The multiplication of $n1 and $n2 is $?"

 

Output:

The following output appears after executing the script for the input 5 and 3. The multiplication result of 5 and 3 is 15:

Go to top

Define a Function that Returns Multiple Values

In the following script, the “echo” command is used in the function to return an array to the caller of the function. A numeric input value is passed as the argument to the function. A loop is iterated to take an input from the user and store it in an array based on the argument value of the function. Then, this array is returned to the function caller. The “read” command is used to store the returned value into an array that is printed later.

#!/bin/bash
#Define a function to return multiple values
return_multiple_values ()
{
   #Declare an array
   declare -a students
   #Iterate the loop to insert values into an array
   for (( i=0; i<$1; i++ ))
   do
       read -p "Enter a student name: " name
       students[$i]=$name
   done
   #Return the array to the caller
   echo ${students[@]}
}

#Take the number of students from the users
read -p "Enter the number of students: " std

#Call the function with one argument
return_array=$(return_multiple_values $std)
#Store the return value in an array
read -a std_arr <<< $return_array

#Print the array values
echo "Array values are:"
for val in "${std_arr[@]}"
do
  echo "$val"
done

 

Output:

The following output appears after executing the script. According to the output, the “Meena”, “Jafar”, and “Sultana” string values are taken from the user and stored in the “$students” array. This array is later returned from the function:

Go to top

Define a Function to Override the Command

Bash has many built-in commands for different purposes. The task of any command can be overridden by writing a Bash function with the name of the command. The script then executes the overridden function in place of the main command. In the following script, the overridden function is written for the “printf” command. Here, the “pritnf” function is called with two arguments which are printed using the “printf” and “echo” commands inside the function.

#!/bin/bash

#Print the output using the builtin `printf` command
printf "%s\n" "Learn Bash Programming."

printf ()
{
    #Print the first argument using `printf`
    builtin printf "%s\n" $1
    #Print the second argument using `echo`
    builtin echo $2
}

#Call the overridden function with two arguments
printf  "Learn bash from LinuxHint" "Shell Programming"

 

Output:

The following output appears after executing the script. In the output, the first message is printed using the “printf” command. Then, each word of the first argument value is printed with the newline and the second argument value is printed in a line after calling the function:

Go to top

Define a Function to Read from a File

The method of reading a file using the Bash function is shown in the following script. A file name is taken from the user. If the file exists, the content of the file is read using the “while” loop after calling the function.

#!/bin/bash

#Take the filename
read -p "Enter a filename: " filename

#Define a function to read the file content
function read_text_file() {
    while read data;
        do
            echo "$data"
        done
} < $filename

echo "The content of the file is given below: "
#Call the function
read_text_file

 

Output:

The following output appears after executing the script with the input value, “test.txt”. The content of this file is printed by executing the script. Then, the “cat” command is used to check the original content of the file which is the same as the output of the script:

Go to top

Define a Function to Write into a File

The method to write into a file using the Bash function is shown in the following script. A file name is taken from the user. The function is called to write three lines into the file. Then, a success message is printed.

#!/bin/bash

#Take the filename
read -p "Enter the filename to create: " filename

function write_into_file()
{
   echo "It is the first line."
   echo "It is the second line."
   echo "It is the third line."

} > $filename

#Call the function to write into the file
write_into_file
echo "File is created successfully."

 

Output:

The following output appears after executing the script with the input value, “test_file.txt”. The “cat” command is later used to check the content of the file:

Go to top

Define a Function to Read the Reference Argument

The reference argument can be passed into the Bash function. In the following script, a year value is taken from the user. Then, the input value is passed as the normal argument and another argument is passed as the reference at the time of calling the function. The function checks whether the year is a leap year or not and stores the message in the reference variable. Then, the reference variable is printed.

#!/bin/bash

#Define a function to use a reference variable
function use_of_reference_var()
{
    #Read the first argument
    year=$1
    #Check whether the year is a leap year or not
    if [ `expr $year % 4` -eq 0 ]
    then
        str="$year is leap year"
    else
        str="$year is not a leap year"
    fi
}

#Take a year value from the user
read -p "Enter a year value: " yr
#Call the function with a normal argument and a reference argument
use_of_reference_var $yr str
#Print the value of the reference variable
echo $str

 

Output:

The following output appears after executing the script with the input value of 2023 which is not a leap year:

Go to top

The following output appears after executing the script with the input value of 2008 which is a leap year:

Go to top

Conclusion

Multiple uses of the Bash function are shown in this tutorial using ten simple Bash examples. The new Bash users will get a clear concept of using the Bash function after reading this tutorial properly.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.