How to create and call functions in Bash

Since we humans made the fantastic discovery of computers, we have been trying to improve it further and further than the last day. This is done through the challenging work of the millions of programmers across the planet and the hundreds of programming languages. Programming works on several fundamental principles, one of which is the usage of functions. Today, we will see how to create a function in Linux’s most popular scripting language, Bash.

Concept

So what are functions, really? Like many things in programming, the concept comes from the mathematical concept of functions. Simply put, functions can be considered machines that take input from one side and present the output according to their job. For example, if we consider the mathematical function of squaring a number:

y = x**2

(Written this way because ** is how an exponent is represented in most programming languages).

If you insert 2 in the “squaring” machine, it will give out 4. If you insert -3, it will give out 9.

Function illustration
Function illustration

In terms of programming, if you need one bit of code to be used repeatedly, you can create a function with that code. Going with our earlier analogy, instead of doing the manual process often, you create a machine that does it for you. All you need to do is give it the necessary information.

Now that we have the explanation let us move on to the actual code.

Syntax of a function

The syntax of defining a function in Bash is similar to that in C. It follows two formats:

function_name () {
//Scope of function
}

The “scope” of a function refers to the body of text that a function includes whatever actions that a function must perform are included in the space of those curly brackets.

The other way to define a function:

function function_name {
//Scope of function
}

This is the same thing, but just a slightly different code. You can use either, as there is no functional difference between the two methods of writing the syntax. So, for example, I am creating a function that prints the classic “Hello World!”:

Hello_World () {
echo "Hello World!"
}

The function is now created. But this isn’t enough just yet. How do you execute the function? How do you make your system understand that it is a Bash script?

Calling a function

Calling a function is even easier than defining one. All you need to do is write the function’s name, and that function will be executed. So as for the function that we just wrote, that prints “Hello World!”, all you need to do to call the function is write:

Hello_World

As that is the name of the function.

Now, as for the execution of the file, there are two ways of doing that:

Extension method

In the extension method, you save the file using the .sh extension and execute it using the bash command. Using the Nano editor, use this command:

nano helloworld.sh
Basic function file
Basic function file

And write the contents as described above. Now save the file by pressing Ctrl+X, Y, and Enter. To execute the file, enter the command:

Basic function execution
Basic function execution
bash helloworld.sh

 

Shebang method

In the second method, we will add a “shebang” at the head of the file. A shebang (#!), followed by the interpreter’s location, tells the system which interpreter to use when the file is executed. So for a Bash script, we will use this shebang:

#!/bin/bash

To create a file using Nano, enter this command:

nano helloworld

(Notice the lack of an extension this time) and write the contents of the file, which, all in all, look like this:

Basic function shebang format
Basic function shebang format

Now to be able to execute this file, we need to save it and add executable permissions to it. To do that, enter the command:

chmod +x helloworld

The “+x” part denotes the addition of executable permissions. Now, finally, to execute the file, enter the following:

./helloworld

(./ is how extension-less executable files are executed in Linux).

Shebang format execution
Shebang format execution

Passing arguments to a function

The functions that we have created and executed so far are the ones that do not require user input, but that is rarely the case for real-life applications of programming. Therefore, we need to be able to use variable inputs in our functions. Returning to our squaring example, let us create a process that requires an input integer and outputs the square of said integer.

square () {
    result=$(($1*$1))
    echo "The square of $1 is: $result"
}

square 2
square -3
Single parameter squaring example
Single parameter squaring example

As seen in the image, the function results are as expected.

Multiple arguments

Bash can even take in multiple arguments. As many as you need. For example, if we want to create a function that adds two numbers, that can be done like this:

add () {
    result=$(($1+$2))
    echo "The sum of the numbers is: $result"
}

add 1 4
Multiple parameters script
Multiple parameters script

Executing this script yields the answer 5, which is the correct sum. Similarly, you can add even more arguments, referring to each with their numeric position, starting with 1. “But what does 0 represent?” you might wonder. Well, see for yourself:

Zero parameter script
Zero parameter script
The zero parameter result
The zero parameter result

The “$0” variable is reserved for the file’s name.

Conclusion

Functions are one of the absolute critical components in the world of programming. Combine the concept with one of the most powerful operating systems in the world, and you have pretty much something on your hands. We hope this article was helpful. Cheers!

AD

Related Articles

1 COMMENT

  1. Hi,

    sometimes it’s also important/helpful in shell scripts to export functions in a Subshell .. to take may for sudo -c “xxxxxxx”
    this can you make with :

    export -f xxxxxxxx

    so “export” the “-f” Function “xxxxxxxxx”/Foo

    this is also helpful if you make scripts for an graphical Surface or so, to call kdesu or some.

    best regards
    Blacky

LEAVE A REPLY

Please enter your comment!
Please enter your name here

SPONSOR AD
22,858FansLike
450FollowersFollow
16SubscribersSubscribe

More Articles Like This