Bash Scripting - Functions
Last Updated :
21 Apr, 2022
A Bash script is a plain text file. This file contains different commands for step-by-step execution. These commands can be written directly into the command line but from a reusability perceptive it is useful to store all of the inter-related commands for a specific task in a single file. We can use that file for executing the set of commands one or more times as per our requirements.
Here in this article, we are going to discuss the use of functions within Bash Scripting.
In programming, A function is a block of code that performs some tasks and it can be called multiple times for performing tasks. It provides modularity in the program and reduces the code length. The simplest example of the use of function in Bash scripting can be given as -
Example script:
#!/bin/bash
#It is a function
myFunction () {
echo Hello World from GeeksforGeeks
}
#function call
myFunction
Output:
Hello World from GeeksforGeeks
The above example shows a function that prints something when called. So, the basic syntax for writing functions within a Bash Script will be
Syntax:
# for defining
function_name(){
commands
.....
}
function_name # for calling
Besides this, we can also have functions with passing arguments and with return values. Now let's discuss them.
Functions with Passing Arguments
We can add arguments or parameters to a function and pass data using it to the function so that the function can act with those data. In bash scripting, we can use the following syntax for writing a function with passing arguments.
Syntax of Functions with Passing Arguments:
#for defining
function_name(){
.....
parameter_1 = $1
parameter_2 = $2
.
.
.
parameter_n = $n
....
commands
.....
}
#for calling
function_name p1 p2 ....pn
We can directly pass the arguments while calling the function and can access them with $1, $2 ..... $n within the function. Let's see an example for more clear understanding of it.
Example of Functions with Passing Arguments:
#!/bin/bash
add_two_num(){
local sum=$(($1+$2))
echo sum of $1 and $2 is $sum
}
add_two_num 2 3
Output of Functions with Passing Arguments:
sum of 2 and 3 is 5
Above is a script for adding two numbers. Here we have provided 2 and 3 as arguments. We have accessed them using $1 and $2 from the function and calculated their sum and printed it to the terminal. Below is the terminal shell depiction after executing the script -
Functions with Return Values
A return value is produced and returned to the calling method by a function after it completes its execution. A return value can be used to share the produced result or some status code about whether one function was successfully executed or not. In Bash scripting, the return value is assigned to the $? variable.
An example of the same is given below -
Example of Functions with Return Values:
#!/bin/bash
myfun(){
return 7
}
myfun
echo The return value is $?
Output of Functions with Return Values:
The return value is 7
Below is the terminal shell output after executing the script -
Now, Let's modify the earlier sum of the two-number script.
Modified Code:
#!/bin/bash
myfun(){
return $(($1+$2))
}
add_two_num 2 3
echo The sum is $?
Output of Modified Code:
The sum is 5
Now the above code is an example of using both parameters and return value in a Bash script function.
Below is the terminal shell depiction after executing the script -
Variable Scope
Scope in a program or script is a region where the variables have their existence. If a variable, is declared inside a function then it is generally a local variable and if it is declared outside then it is a global variable. In the case of a bash script, this concept is a little bit different, here any variable whether it is written inside a function or outside a function by default is a global variable. If we want to make a local variable then we need to use the keyword "local".
It is best practice to always use a local variable inside a function to avoid any unnecessary confusion.
An example of the same is given below -
Example of Variable Scope:
#!/bin/bash
var1="Apple" #global variable
myfun(){
local var2="Banana" #local variable
var3="Cherry" #global variable
echo "The name of first fruit is $var1"
echo "The name of second fruit is $var2"
}
myfun #calling function
echo "The name of first fruit is $var1"
#trying to access local variable
echo "The name of second fruit is $var2"
echo "The name of third fruit is $var3"
Output of Variable Scope:
The name of first fruit is Apple
The name of second fruit is Banana
The name of first fruit is Apple
The name of second fruit is
The name of third fruit is Cherry
Here in this above example, var2 is a local variable, so when we are accessing it from the function it is doing fine but when we are trying to access it outside the function, it is giving us an empty result in the output.
On the other hand, unlike programming languages, even though var3 is defined inside a function still it is acting as a global variable and it can be accessed outside the function. Below is the terminal shell depiction after executing the script -
Overriding Commands
It is possible to have a function with the same name as that of a command. It is helpful if we want to run a command with specific options or want to have a customized edition of it.
An example of the same is given below -
Example of Overriding Commands:
#!/bin/bash
#overriding command
echo(){
builtin echo "The name is : $1"
}
echo "Satyajit Ghosh"
Output of Overriding Commands:
The name is : Satyajit Ghosh
Here in this example, we have overridden the echo command. Now before printing the given string, it appends the string with some more words and then prints. Below is the terminal shell depiction after executing the script -
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
Linux Commands Cheat Sheet Linux, often associated with being a complex operating system primarily used by developers, may not necessarily fit that description entirely. While it can initially appear challenging for beginners, once you immerse yourself in the Linux world, you may find it difficult to return to your previous W
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read