bash functions

Bash scripting the awesome guide part6 Bash functions

Before we talk about bash functions, let’s discuss this situation. When writing bash scripts, you’ll find yourself that you are using the same code in multiple places.

If you get tired of writing the same blocks of code over and over in your bash script, it would be nice to write the block of code once and refer to it anywhere in your bash script without having to rewrite it.

The bash shell provides a feature allowing you to do just that called Functions.

Bash functions are blocks of code that you assign a name to them and reuse them anywhere in your code. Anytime you want to use this block of code in your script, you simply type the function name given to it.

We are going to talk about how to create your own bash functions and how to use them in shell scripts.


Creating a function

You can create a function like this:

functionName {


Or like this:

functionName() {


The parenthesis on the second snippets is used to pass values to the function from outside of it, so these values can be used inside the function.

Using functions

Here we’ve created a function called myfunc and in order to call it, we just typed its name.

bash functions

The function can be called many times as you want.

Notice: If you attempt to use a function before it’s defined, you’ll get an error message.

bash functions call before declare

Another notice: bash function name must be unique, or you’ll have a problem. If you redefine a function, the new definition overrides the original function definition without any errors.

bash functions override definition

As you can see, the second function definition takes control from the first one without any error so take care when defining functions.

Using the return command

The return command allows you to specify a single integer value to define the function exit status.

There are two ways of using return command; the first way is like this:

bash functions return command

The myfunc function adds 10 to the value contained in the $value variable provided by the user input. Then it returns the result using the return command, which is displayed using the $? Variable.

If you execute any other commands before retrieving the value of the function using the $? variable, the return value from the function will be lost. The reason is that the $? Variable returns the exit status of the last executed command.

You cannot use this return value method if you need to return larger integer values or a string value.

Using function output

The second way of returning a value from a bash function is to capture the output of a command and save it to a variable. You can use this technique to retrieve any type of output from a function.

bash functions output

Passing parameters to a function

We can deal with bash functions like small snippets that can be reused and that’s OK, but we need to make the function like an engine, we give it something and it returns a result based on what we provide.

Functions can use the standard parameter environment variables to represent any parameters passed to the function on the command line. For example, the name of the function is defined as $0 variable, and any other parameters passed to the function command line are defined using the variables $1, $2, and so on. You can also use the special variable $# to determine the number of parameters passed to the function. I recommend you to review the previous posts to empower your knowledge about them Linux bash scripting.

We pass parameters to functions on the same command line like this:

myfunc $val1 10 20

The following example shows you how to retrieve the parameter values using the parameter environment variables:

bash functions pass parameters

The addnum function checks the number of parameters passed to it. If there are no parameters passed, or if there are more than two parameters, addnum returns a value of -1.

If there’s one parameter, the addnum function adds it to itself for the result. If there are two parameters, the addnum function adds them together, and if you try to add three parameters it will return -1.

You can’t directly access the script parameter values from within the function. The following example fails:

bash functions unknown parameters

Instead, if you want to use these values in your bash function, you have to pass them when you call the function like this:

bash functions parameters

Now they are available for the function to use, just like any other parameter.

Handling variables in bash functions

Every variable we use has a scope, the scope is where the variable is visible.

Variables defined inside functions can have a different scope than regular variables.

They can be hidden from the rest of the script.

There are two types of variables:

  • Global
  • Local

Global variables

Global variables are visible and valid anywhere in the bash script. If you define a global variable in the main section of a script, you can retrieve its value inside a function.

The same, if you define a global variable inside a function, you can retrieve its value in the main section of the script.

By default, any variables you define in the script are global variables. Variables defined outside of a function can be accessed inside the function without problems:

bash functions global variables

When the variable is assigned a new value inside the function, that new value is still valid when the script references the variable as the above example, the variable $value is changed inside the function.

So how to overcome something like this? Use local variables.

Local variables

Any variables that the bash function uses internally can be declared as local variables. To do that, use the local keyword in front of the variable like this:

local temp=$(( $value + 5 ))

If a variable with the same name found outside the function in the script, the shell will keep both variable values separate. Now you can easily keep your function variables separate from your script variables:

bash functions local variables

When you use the $temp variable inside the myfunc function, it doesn’t affect the value assigned to the $temp variable in the main script.

Passing arrays to functions

The art of passing an array variable to a bash function can be confusing. If you try to pass the array variable as a single parameter, it doesn’t work:

bash functions pass arrays

If you try using the array variable as a function parameter, the function only picks up the first value of the array variable.

To solve this problem, you must disassemble the array into its single values and use these values as function parameters. Inside the function, you can reassemble all the parameters into a new array variable like this:

bash functions pass arrays solution

The function rebuilds the array variable from the command line parameters.

Recursive function

This feature enables the function to call itself from within the function itself.

The classic example of a recursive function is calculating factorials. A factorial of a number is the value of the preceding numbers multiplied with the number. Thus, to find the factorial of 5, you’d perform the following equation:

5! = 1 * 2 * 3 * 4 * 5

Using recursion, the equation is reduced down to the following format:

x! = x * (x-1)!

So to write the factorial function using bash scripting, it will be like this:

bash recursive function

Using recursive bash functions is so easy!

Creating libraries

Now we know how to write functions and how to call them, but what if you want to use these bash functions or blocks of code on different bash script files without copying and pasting it on your files.

The bash shell allows you to create a library file for your functions and then reference that single library file in many scripts as you need.

You can use the source command to run the library file script inside your shell script. This makes the functions available to the script.

The source command has a shortcut alias, called the dot operator. To source a file in a shell script, you just need to add the following line:

. ./myscript

Let’s assume that we have a file called myfuncs that contains the following:

Now, we will use it in another bash script file like this:

bash functions source command

Awesome!! We’ve used the bash functions inside our bash script file, but what if we want to use these functions from our bash shell directly?

Use bash functions from command line

Well, that is easy, if you read the previous post which was about the signals and jobs you will have an idea about how to source our functions file in the .bashrc file and hence we can use the functions directly from the bash shell. Cool

Edit the .bashrc file and add this line:

. /home/likegeeks/Desktop/myfuncs

Make sure you type the correct path.

Now the function is available for us to use in the command line directly:

$ addnum 10 20

bash functions use from shell

Even better, the shell also passes any defined bash functions to child shell processes so your functions are automatically available for any bash scripts without sourcing, wow!! That’s really cool, right?

Note: you may need to logout and login to use the bash functions from the shell.

Another note: if you make your function name like any of the built-in commands you will overwrite the default command so you should take care of that.

I hope you like the post. Keep coming back

Thank you.