Exploring Bash — Part 5

Dineshkumaar R
7 min readApr 10, 2024

--

Introduction

Hey Friends, Welcome back to my Bash exploration blog series! Today, we’ll delve into the power of Bash functions. These handy tools encapsulate code for reuse, enhancing modularity and maintainability. Let’s dive right in!

Functions

Functions in Bash allow you to encapsulate a block of code for reuse. They improve code modularity and maintainability by allowing you to break down complex tasks into smaller, more manageable chunks.

Defining a function

function_name() {
# commands to execute
}

Explanation:

function_name: This is the name you choose for your function. It follows the same naming rules as variable names in Bash.
(): These parentheses indicate that you’re defining a function.
{}: These curly braces contain the body of the function, where you write the commands that the function will execute.

Example:

name() {
echo "Hello, Dinesh!"
}

# Call the name function
name

“The script defines a function called ‘name’ that prints a message, and then it calls the ‘name’ function. As a result, the output of running the script is ‘Hello, Dinesh!’.”

Function Parameters

Function parameters allow you to pass values to functions when they are called. Positional parameters (`$1`, `$2`, etc.) hold the values passed to the function, while special variables (`$@`, `$*`) represent all the arguments passed.

Example 1:

# Define a function called 'sum' which takes two numbers as parameters
sum() {
local result=$(( $1 + $2 )) # Calculate the sum of the two numbers
echo "The sum of $1 and $2 is: $result"
}

# Call the 'sum' function with two numbers: 10 and 20
sum 10 20

• We define a function named sum.
• The function takes two parameters, $1 and $2, representing the two numbers to be added.
• Inside the function, we calculate the sum of the two numbers using arithmetic expansion ($(( ))) and store the result in a local variable result.
• We then use echo to print the result along with the numbers passed as parameters.
• Finally, we call the sum function with the arguments 10 and 20.
• When the script runs, it will output: The sum of 10 and 20 is: 30.

Example 2:

# Define a function called 'print_args' to print all the arguments passed to it
print_args() {
echo "All arguments passed individually:"
for arg in "$@"; do
echo "$arg"
done

echo "All arguments passed as a single string:"
echo "$*"
echo "Total $# arguments passed"
}

# Call the 'print_args' function with multiple arguments
print_args "apple" "banana" "cherry"

• We define a function named print_args which prints all the arguments passed to it.
• The for loop iterates through each argument passed to the function (“$@”) and prints them individually.
• We use “$*” to print all the arguments as a single string.
• $# represents the total number of arguments passed to the function.

When the function print_args is called with multiple arguments (“apple”, “banana”, “cherry”), it prints each argument individually, then prints all the arguments as a single string, and finally displays the total number of arguments passed.

Returning Values

Functions can return values using the ‘return’ statement. The returned value can then be captured and used in the calling code.

Example 1:

add() {
return $(($1 + $2))
}

add 5 3
result=$?
echo "Result: $result"

• The add function is defined to calculate the sum of two numbers.
• Inside the function, return $(($1 + $2)) calculates the sum of the two numbers passed as arguments and returns the result.
• The add 5 3 line calls the add function with arguments 5 and 3.
• After calling the function, $? holds the return value of the function, which is the result of the addition operation.
• Finally, echo “Result: $result” prints the result.

Example 2:

#!/bin/bash

# Define a function named 'factorial' to calculate the factorial of a number
factorial() {
local num=$1 # Store the number passed as an argument
local result=1 # Initialize the result variable to 1
for ((i = 1; i <= num; i++)); do
((result *= i)) # Multiply result by current value of i
done
return $result # Return the calculated factorial
}

# Prompt the user to enter a number
echo -n "Enter a number to calculate its factorial:"
read user_num

# Call the 'factorial' function with the user's number
factorial $user_num

# Capture the return value
factorial_result=$?

# Print the result
echo "The factorial of $user_num is: $factorial_result"

• The script defines a Bash function named factorial to calculate the factorial of a number.
• It prompts the user to enter a number.
• The entered number is passed to the factorial function.
• The function calculates the factorial of the number and returns the result.
• The return value is captured and stored in the variable factorial_result.
• The script prints the calculated factorial value for the entered number.

Note: The script uses a return statement in the factorial function, but Bash functions return exit status codes rather than direct values, so the return statement doesn’t work as intended for returning the factorial value. Instead, we capture the exit status of the function using $? after the function call.

Function Scope

Variables defined within a function have local scope by default, meaning they are only accessible within that function. This helps prevent variable name clashes and unintended side effects.

#!/bin/bash

# Global variable
message="I am Global"

# Function to modify message
modify_message() {
local message="I am Local" # Local variable within the function
echo "Inside function: $message" # Printing local message variable
}

# Calling the function
modify_message

# Printing global message variable outside the function
echo "Outside function: $message"

• We have a global variable message set to “Hello, World!”.
• The modify_message function defines a local variable message set to “Goodbye, World!”.
• Inside the function, it prints the value of the local message variable.
• After calling the function, we print the value of the global message variable outside the function.
• Despite modifying the value of message inside the function, it only affects the local scope of the function, and the global message variable remains unchanged.

Recursive Functions

Recursive functions in Bash are functions that call themselves to solve a problem. They are useful for tasks that can be broken down into smaller subproblems.

Example

#!/bin/bash

# Define a function to calculate the Fibonacci sequence recursively
fibonacci() {
local n=$1

# Base case: If n is 0 or 1, return n
if [ $n -eq 0 ] || [ $n -eq 1 ]; then
echo $n
else
# Recursive case: Fibonacci(n) = Fibonacci(n-1) + Fibonacci(n-2)
echo $(( $(fibonacci $((n - 1))) + $(fibonacci $((n - 2))) ))
fi
}

# Calculate and print the Fibonacci sequence for the first 10 numbers
for ((i = 0; i < 10; i++)); do
result=$(fibonacci $i)
echo "Fibonacci of $i: $result"
done

• Recursive function calculates Fibonacci numbers.
• Takes an argument n representing the position.
• Base cases: If n is 0 or 1, returns n.
• Recursive cases: Calculates Fibonacci(n-1) and Fibonacci(n-2), returns their sum.
• Main loop iterates through first 10 numbers.
• Function called with current position in loop.
• Prints Fibonacci number for each position.

Summary of the blog

1. Functions: Bash functions encapsulate blocks of code for reuse, improving modularity and maintainability.
2. Defining a function: Use the syntax function_name() { … }, where function_name is the chosen name, followed by parentheses and curly braces containing the code.
3. Function Parameters: Parameters are passed using positional variables ($1, $2, etc.) or special variables ($@, $*) to represent all arguments.
4. Returning Values: Functions can return values using the return statement, which can be captured and used in the calling code.
5. Function Scope: Variables within functions have local scope by default, preventing clashes and unintended side effects with global variables.
6. Recursive Functions: Bash supports recursive functions, which call themselves to solve problems, useful for tasks that can be broken into smaller subproblems.

URL’s :

  1. Exploring bash — Part1 : https://medium.com/@dineshkumaar478/exploring-bash-part-1-3dabf4b5ef9e
  2. Exploring bash — Part2 : https://medium.com/@dineshkumaar478/exploring-bash-part-2-71f341fb5700
  3. Exploring bash — Part3 : https://medium.com/@dineshkumaar478/exploring-bash-part-3-db1fc958eb17
  4. Exploring bash — Part4 : https://medium.com/@dineshkumaar478/exploring-bash-part-4-4521aaac30ea

Thank you for taking the time to read my blog. Wishing you a joyful learning experience ahead!

--

--

Dineshkumaar R

🔐 Cyber Security Engineer | Penetration Tester | VAPT Specialist | 🚩 Hackthebox (Pro Hacker) | 🏆 Tryhackme (Guru)