bash functions

Bash Scripting Part6 – Create and Use 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 allows you to do just that with 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. Otherwise, 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 enables 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 display the result using the $? Variable.

Keep in mind that you will lose the return value from the function if you execute any other commands before getting the value of the function using the $? variable. 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. This way, you can return anything from the 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 deal with any parameters passed to the function on the command line. For example, the function name is defined as $0 variable, and the passed parameters are $1, $2, and so on.

The special variable $# is used 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.

But if you define variables inside functions, they will have a different scope than regular variables.

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 your script, you can get its value inside a function.

If you assign a global variable inside a function, you can get its value in the main section of the script.

By default, any variables you define in the script are global variables. If you define a variable outside the function, you call it inside the function without problems:

bash functions global variables

When the variable takes a new value inside the function, 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.

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 problematic. If you try to pass an array variable as a single parameter, it doesn’t work:

bash functions pass arrays

The function only takes the first value of the array variable.

You should disassemble the array into its single values, then use these values as function parameters. Finally, you can reassemble all the parameters into a new array variable in the function like this:

bash functions pass arrays solution

The array variable was rebuilt thanks to the function.

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. To calculate the factorial of 5, use 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 enables you to create a library file for your functions and then reference that single library file in many scripts as you need.

By using the source command, you can embed the library file script inside your shell script.

The source command has an alias which is the dot. To source a file in a shell script, write 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.