Bash Function & How to Use It {Variables, Arguments, Return}


Bash functions are an essential feature of Bash shell, allowing you to group commands and reuse them throughout your scripts. A Bash function is essentially a block of code that can be called and executed at any point in your script. In this article, we will explore basics of Bash functions and learn how to use them effectively.

Defining a Bash Function

To define a Bash function, you need to use function keyword followed by name of your function and code that you want to execute. Here's an example of how to define a simple Bash function −

function greet {
  echo "Hello, World!"
}

In this example, we have defined a Bash function called greet that simply prints "Hello, World!" to console. To execute this function, you can simply call it by its name −

greet

When you execute this command, you will see output "Hello, World!" printed to console.

Passing Arguments to a Bash Function

Bash functions can also accept arguments, which can be passed in when function is called. To pass an argument to a Bash function, simply include it after function name, separated by a space. Here's an example of a Bash function that accepts an argument −

function greet {
  echo "Hello, $1!"
}

In this example, we have updated greet function to accept an argument, which is referenced using $1 variable. This variable represents first argument passed to function. To call this function with an argument, simply include argument after function name −

greet "Alice"

When you execute this command, you will see output "Hello, Alice!" printed to console.

Using Variables in a Bash Function

Bash functions can also use variables to store and manipulate data. To define a variable inside a Bash function, simply use = operator followed by value you want to assign to variable. Here's an example of a Bash function that uses a variable −

function greet {
   name=$1
   echo "Hello, $name!"
}

In this example, we have defined a variable called name inside greet function and assigned it value of first argument passed to function. We then use this variable in echo command to print a personalized greeting to console.

Returning Values from a Bash Function

Bash functions can also return values, which can be stored in a variable or used directly in your script. To return a value from a Bash function, simply use return keyword followed by value you want to return. Here's an example of a Bash function that returns a value −

function add {
   sum=$(( $1 + $2 ))
   return $sum
}

In this example, we have defined a Bash function called add that takes two arguments, adds them together, and returns sum. We store sum in a variable called sum and use return keyword to return value.

To use value returned by a Bash function, you can assign it to a variable or use it directly in your script. Here's an example of how to use add function −

result=$(add 2 3)
echo "The sum is: $result"

In this example, we call add function with arguments 2 and 3 and assign result to a variable called result. We then use echo command to print value of result to console.

Here are some additional tips and best practices for working with Bash functions

  • Use descriptive names for your functions − This will make your code more readable and easier to understand.

  • Keep your functions short and focused − Each function should have a single responsibility and perform a specific task. This will make it easier to test and debug your code.

  • Use local variables − When defining variables inside a function, use local keyword to ensure that they are only accessible within function and not in global scope.

  • Check for errors and handle them gracefully − Use error checking and handling techniques such as if statement, exit command, and trap command to ensure that your functions behave correctly in all situations.

  • Document your functions − Use comments to describe what each function does, what parameters it takes, and what it returns. This will make your code more understandable to others and to your future self.

  • Test your functions − Use a testing framework such as bash_unit to ensure that your functions work correctly and produce expected output.

Example 

Here's an example of how to use some of these best practices in a Bash script

#!/bin/bash

# Define a function to add two numbers
function add {
   local num1=$1
   local num2=$2
  
   # Check that both arguments are numbers
   if ! [[ "$num1" =~ ^[0-9]+$ ]]; then
      echo "Error: Argument 1 is not a number"
      exit 1
   fi
  
   if ! [[ "$num2" =~ ^[0-9]+$ ]]; then
      echo "Error: Argument 2 is not a number"
      exit 1
   fi
  
   local sum=$(( num1 + num2 ))
  
   echo $sum
}

# Call add function with two arguments
result=$(add 10 20)

echo "The result is: $result"

In this example, we define a function called add that takes two arguments and returns their sum. We use local keyword to define two variables num1 and num2 inside function, and check that they are both valid numbers using if statement. We then use echo command to print sum to console. Finally, we call add function with arguments 10 and 20, and store result in a variable called result. We then use echo command to print result to console.

By following these best practices and incorporating them into your Bash scripts, you can write more robust, reliable, and maintainable code.

Conclusion

In conclusion, Bash functions are a powerful feature of Bash shell that allow you to group commands and reuse them throughout your scripts. With Bash functions, you can pass arguments, use variables, and return values, making your scripts more modular and easier to read and maintain. By mastering Bash functions, you can write more efficient and effective Bash scripts and automate tasks with ease.

To summarize key points covered in this article, here are some sub-headings −

Defining a Bash Function
Passing Arguments to a Bash Function
Using Variables in a Bash Function
Returning Values from a Bash Function

By following examples and guidelines outlined in this article, you should now have a solid understanding of how to use Bash functions in your scripts. Remember to experiment with different functions and try out new techniques to find best approach for your specific needs. With practice and persistence, you'll be able to create powerful Bash scripts that can automate complex tasks and streamline your workflow.

Updated on: 31-Mar-2023

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements