In almost all programming language we make use of function which is nothing but the code written as logical block for executing repetitive or recurring execution. In shell programming also we do have something called as bash function which acts the same way.In this post we will be learning more about bash function.
Basic structure of Bash function
function_name ( ) { <command1> <command2> <command3> . . . <commandN> }
The above structure or basic building block of the bash function is also called as defining a bash function. Make sure you define this bash function before you call it to anywhere.
Sample Bash function
[root@rhel1 tmp]# cat function1.sh #!/bin/bash # Basic function print () { echo Hello UxTechno from Basic Function } print [root@rhel1 tmp]#
In the above example we have written bash function “print ()” which prints or echo’s sample message when it is called. As mentioned above we have function print ( ) and then called it using print command below the function.
Now let’s move to execution part of it.
[root@rhel1 tmp]# chmod u+x function1.sh [root@rhel1 tmp]# ./function1.sh Hello UxTechno from Basic Function [root@rhel1 tmp]
In the above code we made the shell script function1.sh executable using chmod command. And as usual we have executed the script using “./” followed by name of the shell script.
Passing Arguments or Parameters
Unlike famous programming language like c or java we also can pass an arguments or parameters in bash scripting. Let’s take example for passing an argument or parameter with function.
[root@rhel1 tmp]# cat ./function2.sh #!/bin/bash # Argument or Parameter passing print () { echo Hello $1 from UxTechno } print RedHat_users print Ubuntu_users [root@rhel1 tmp]#
This is the same function which we have used is sample function, However this time we are passing two parameters or arguments RedHat_users and Ubuntu_users to the function print( ). And this argument we are using it while echoing the message.
Lets execute the function to see the result.
[root@rhel1 tmp]# ./function2.sh Hello RedHat_users from UxTechno Hello Ubuntu_users from UxTechno [root@rhel1 tmp]#
Returning values using Bash function
Unlike major programming language we can use return value which is used for sending back the data value to the calling location.
Leave a Reply