
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Bash Function in Linux
Have you ever wondered how to accelerate your daily Linux system administration tasks in an efficient and simpler way? If yes, then you might probably heard that Bash (Your Daily Linux Shell) and as any interpreter out there has a lot which can be used to automate various Linux-related tasks. In this tutorial, we will explain how to use one of the built-ins in Bash (Functions) to get your task quickly done.
Table of Contents
- What are Bash Functions?
- Benefits of using Bash Functions
- Getting started with Bash Functions
- General Bash Functions Syntax
- Advanced Bash Function Concepts
- Level Up Bash Function with these techniques
What are Bash Functions?
In fact we can consider Bash functions as a named block of code that performs a specific task/tasks, simplifies scripting on Linux, improves the readability of the Linux commands and save time which leads to boost productivity.
Benefits of using Bash Functions
Talking about why I should use Bash Functions, it's because of the following benefits
- Simplifying scripting ? No-doubt that when you embed bash function in your scripts it will make your code readable, easy to understand and of course more simplified.
- Reduce duplication ? You don't need to write the code again and again while you can simply use a function and call it everywhere in your script and this is what's known as reusing your code instead of rewriting.
- Enhanced maintainability ? From time to another you might want to update or modify your scripts, using functions will give us the ability to tailor the script to your specific needs and preferences.
Getting Started with Bash Functions
The general syntax for defining a Bash function is straightforward ?
function function_name { # Commands to be executed within the function }
Alternatively, you can remove the function keyword ?
function_name() { # Commands to be executed within the function }
Take a look at the following simple example ?
function my_function { echo "Hello TutorialsPoint"; }
As you can see from the above example, declaring a bash function goes through four steps ?
The first line refers to the name of the function, and here there are two different formats. The first format starts with the reserved word function, followed by the function name, like this ?
function function_name
The second format starts with the function name, followed by parentheses, and this is the preferred and most used format, just like this
function_name()
The second line is that curly brace { which marks the start of the function's body. The third line is the actual function body. The function body can contain multiple commands, statements, and variable declarations. The last line is the closing curly bracket } that defines the end of the function.
Calling a Bash Function
Now you might ask, I knew how to declare a function, but how I can use it in my script? Well, this process is known as Calling a Bash Function. To execute a function, simply call it by its name. For example we have the above function
function my_function { echo "Hello TutorialsPoint"; } my_function;
As you can see this function does only one job, which is printing Hello TutorialsPoint. So, if you want to print this phrase in any part in your script, simply write the name of the function ?
my_function
That's it; as simple as you see.
Note ? If a # sign precedes a line, it means that this line is just a comment and has no effect on the code.
Advanced Bash Function Concepts
Passing Arguments ? We all know that a Linux command line argument does exist to provide additional information or options to the command, allowing it to perform different actions or behave in different ways. Here we can also pass arguments to the function to change its behavior. In this section, let's understand how to pass arguments to a Bash function.
When you want to pass an argument to your function, all what you have to do is supplying the argument directly after the function name, separated by a space.
But keep in mind that these arguments will be accessed using positional parameters, which in turn exists within the function body itself. These positional parameters are $1, $2, $3 ? $n, and each one of these positional parameters correspond to the position of the parameter which will be represented by the argument after the function's name.
Example
Take a look at the following example ?
function say_hello() { echo "Hello, " $1! }
Now let's call this function with a parameter, like shown below ?
say_hello "There"
It will print the following output ?
Hello, There!
Here's another example with two positional parameters ?
myfunction() { echo "Hello,"$1 - "Hello,"$2; }
Let's call this function with two parameters, as follows ?
myfunction "Ahmed" "Mohamed";
In this example, $1 as a positional parameter will be represented by the first argument passed to the function which in this case will hold the value of "Ahmed". And the second positional parameter $2 will hold the value of the second argument which in this case "Mohamed".
So, the function will print the following output ?
Hello, Ahmed - Hello,Mohamed
You can read more about these positional parameters from the man page, type the following command in your Linux shell ?
[ahmed@RHEL-PC ~]$ man 1 bash
Returning Values from a Bash Function
A Bash function does not have its own dedicated return statement. When a bash function completes, its return value is the status of the last statement executed in the function, 0 for success and non-zero decimal number in the 1 - 255 range for failure.
Take a look at the following example ?
testing_function () { echo "Use GNU/Linux" return 99 }
Let's call this function as follows ?
testing_function echo $?
The output will be ?
Use GNU/Linux 99
Scope of the Variables
There's two types regarding the scope of the variable: Global and Local. By default, a variable is global, which means it's accessible from anywhere in the script, but sometimes, we may need to add a variable that is accessible only within a function. In such cases, we use the reserved word local followed by the name of the variable.
Note ? You can have local variables with the same name in different functions.
Example
Take a look at the following example ?
#!/bin/bash var1="Arch Linux" var2="Ubuntu" function testing_variable_scope() { local var1="RHEL" echo "Please use $var1 as your daily Operating System" } testing_variable_scope; echo "$var1 is a rolling distribution, Use $var2 OS for gaming";
The above bash script starts by defining two variables var1 and var2 as global variables with predefined values. After that, there's a function named testing_variable_scope and inside it, there's a local variable named var1 but in fact, this local variable will override the global var1 but also within the function scope. Finally, we are calling that function and we are printing an echo statement that has $var1 and $var2 as global variables.
So, the output of this script will be ?
Please use RHEL as your daily Operating System Arch Linux is a rolling distribution, Use Ubuntu OS for gaming
Best Practices to Level Up Bash Functions
These are some of best practices and techniques to level up Bash functions. Writing good functions that make your script easier to maintain is an awesome skill, so consider the following while writing a Bash Function ?
- Use descriptive names ? You've to clearly indicate function purpose.
- Keep functions short ? Use 10 to 20 lines maximum.
- Comment code ? Highly important to use comments to explain complex logic.
- Function Debugging ? Use the set -x command to enable debugging mode and trace the execution of your functions.
Conclusion
In this tutorial, we explored how using Bash Function can empower you whether you're a Linux System Administrator or a GNU/Linux user to streamline scripting and how the code can be more improved and organized.