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 –
Bash Scripting – Functions
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 w3wiki } #function call myFunction
Output:
Hello World from w3wiki
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.