Bash Scripting - Functions
Last Updated :
12 Sep, 2024
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
Bash Script - Features
These days, there are various shell writing options available out there, and each one of them has its own unique features. Just as it does, Bash Shell contains some of the best features that make it more productive and usable. For each project, there are specific requirements for the features, and t
3 min read
Graphing Function
Graphing Function is the process of illustrating the graph (the curve) for the function that corresponds to it. Plotting simple functions like linear, quadratic, cubic, et al. examples doesnât pose a challenge; depicting functions of a more complex nature like rational, logarithmic, and others requi
13 min read
Shell Scripting - Functions and it's types
Shell scripting is a powerful tool used to automate tasks in Unix-like operating systems. A shell serves as a command-line interpreter, and shell scripts often perform file manipulation, program execution, and text output. Here, we'll look into functions in shell scripting, exploring their structure
5 min read
Scripts and Functions in MATLAB
In MATLAB there are a different kinds of files dedicated to MATLAB codes. They are the following: ScriptLive ScriptFunction only fileClass fileNow only the live script is the only one of these which has a different extension name; all other three use the standard .m extension. In this article, we sh
2 min read
Shell Scripting - Define #!/bin/bash
A shell provides an interface to connect with the system. When we use an operating system, we indirectly interact with the shell. While using a terminal every time on any Linux distribution system, we interact with the shell. The main function of the shell is to interpret or analyze Unix commands. A
3 min read
Python Functions
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or repeatedly done tasks together and make a function so that instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it ov
11 min read
TypeScript Functions Type
TypeScript function types define the structure of a function, including its parameter types and return type, ensuring consistent and type-safe usage.Help validate the types of parameters passed to a function.Ensure the function returns the expected type.Improve code clarity and prevent runtime error
6 min read
Bash Scripting - Case Statement
A case statement in bash scripts is used when a decision has to be made against multiple choices. In other words, it is useful when an expression has the possibility to have multiple values. This methodology can be seen as a replacement for multiple if-statements in a script. Case statements have an
8 min read
TypeScript Anonymous Functions Type
In TypeScript, an Anonymous Function Type defines a function without a specific name, specifying parameters and return types. This allows for flexible and reusable function definitions, enabling the assignment of functions to variables and the use of type annotations for parameters and return values
3 min read
JavaScript function* expression
The function* is an inbuilt keyword in JavaScript which is used to define a generator function inside an expression. Syntax: function* [name]([param1[, param2[, ..., paramN]]]) { statements}Parameters: This function accepts the following parameter as mentioned above and described below: name: This p
2 min read