Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Quick Guide: How to write Bash function

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 ( ) {


.
.
.


}

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

[[email protected] tmp]# cat function1.sh
#!/bin/bash
# Basic function
print () {
echo Hello UxTechno from Basic Function
}
print
[[email protected] 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.

[[email protected] tmp]# chmod u+x function1.sh
[[email protected] tmp]# ./function1.sh
Hello UxTechno from Basic Function
[[email protected] 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.

[[email protected] tmp]# cat ./function2.sh
#!/bin/bash
# Argument or Parameter passing
print () {
echo Hello $1 from UxTechno
}
print RedHat_users
print Ubuntu_users
[[email protected] 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.

[[email protected] tmp]# ./function2.sh
Hello RedHat_users from UxTechno
Hello Ubuntu_users from UxTechno
[[email protected] 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.

The post Quick Guide: How to write Bash function appeared first on UX Techno.



This post first appeared on UxTechno, please read the originial post: here

Share the post

Quick Guide: How to write Bash function

×

Subscribe to Uxtechno

Get updates delivered right to your inbox!

Thank you for your subscription

×