Bash Function Examples

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

Bash scripting is the process of writing scripts using the bash language primarily found in Unix-based systems like Linux. The bash function is an integral component of bash scripting. It allows users to encapsulate sets of commands or operations into reusable blocks of code. Which enhances the script’s modularity, readability, and maintainability. This article will showcase some of the common bash function examples.

What is Bash Function?

The function is a set of commands grouped together as a block to perform a specific task in the Bash scripting. It can accept parameters, process data, and return results just like functions in other programming languages. It allows the organization and reuse of code effectively. Here’s the basic syntax to define a function in Bash:

function_name() {
  # Commands to be executed
}

Here, function_name is the name of the function, followed by parentheses (). Within the curly braces {}, the commands that constitute the function’s body are specified. When the function is called, Bash executes the commands defined within its body.

16 Bash Function Examples

In the realm of bash scripting functions play a pivotal role in streamlining code, enhancing readability, fostering code reusability, etc. Whether you want to greet users dynamically, compute factorials recursively, manipulate strings, or want to do file operations or directory management, all can be seamlessly done using the bash functions. This article will dive into 16 practical bash function examples with a clear explanation of those use cases.

1. Basic Bash Function With Optional Input

The function can be used in bash scripting to handle user arguments. It can be set in a way so that it can use a default value when no argument is given. The following script showcases how to use the function with no argument, single argument, and optional argument:

#!/bin/bash

# Function to handle default greeting
default_greeting() {
  echo "Hello, welcome to the Bash Functions Example!"
}

# Function to greet the user with name
greet_user() {
  echo "Hello, $1! Welcome to the Bash Functions Example!"
}

# Function to greet the user with an optional name
greet_optional() {
  local name=${1:-"Guest"}
  greet_user "$name"
}

# Invoke the functions
default_greeting
greet_user "Sam"
greet_optional
greet_optional "Sam"
EXPLANATION

The script is a Bash shell program designed to greet users in different scenarios. It defines three functions: default_greeting, greet_user, and greet_optional. The default_greeting function prints a standard welcome message, greet_user greets users by their provided name, and greet_optional allows for a default greeting if no name is provided, and also if any name is provided then it greets users by their name. The script then calls these functions to demonstrate each greeting scenario.

bash function with no input, single input and optional input

Here, multiple bash functions display different greetings based on the different arguments.

2. Adding Numbers Using Function

The bash function can be used to simplify different complex mathematical operations. In the following example, a function was used to add 2 numbers. Here is the code to do so:

#!/bin/bash

# Define a function to add two numbers
add_numbers() {
  sum=$(($1 + $2))
  echo $sum
}

# Call the function and store the result
result=$(add_numbers 10 5)
echo "The sum is: $result"
EXPLANATION

This Bash script defines a function named add_numbers that takes two parameters and calculates their sum using the arithmetic expansion operator $((...)). The sum is stored in a variable named sum, which is then echoed back as the result. The script calls the add_numbers function with arguments 10 and 5, stores the returned sum in the result variable, and then echoes the sum into the console.

add numbers using function

Here, this script echoes the sum of numbers 10 and 5 in the terminal.

3. Performing Multiplication With Local Variables

A local variable in bash is a variable that is defined and accessible only within the scope of a specific function or script. That means this local variable can not be accessed or modified from the outside of that particular scope. It serves to encapsulate data, keeping it confined to the function where it is defined, thus preventing accidental modification or interference with other parts of the script. The local variables are used to multiply 2 numbers in this example:

#!/bin/bash

# Define a function with local variables
multiply() {
  local x=$1
  local y=$2
  local result=$(( x * y ))
  echo "Result: $result"
}

# Call the function with arguments
multiply 3 6
EXPLANATION

This Bash script showcases a function named multiply() in which the parameters $1 and $2 are assigned to local variables x and y, respectively. Using these variables, the function computes the product of x and y and stores the result in the result variable. Finally, it prints the calculated result to the console with the message “Result: [value]”. After executing the script with the arguments 3 and 6 provided to the multiply() function, it outputs “Result: 18”.

Performing Multiplication With Local Variables inside function

Here, the script prints the multiplication of 3 and 6 in the terminal using 3 local variables.

4. Calculating Factorial Using Recursive Function

A recursive function is a function that calls itself within its definition. In Bash programming, recursion is a technique where a function solves a problem by calling itself with smaller instances of the same problem. Recursive functions have two main components: a base condition, which determines when the recursion should stop, and a recursive condition, where the function calls itself with modified inputs to eventually reach the base condition. This technique is commonly used in solving problems that can be broken down into smaller, similar subproblems. Factorial is among one of those problems.

Here is how to calculate the factorial of a number using a recursive function:

#!/bin/bash

# Define the factorial function
factorial() {
  if [ $1 -eq 0 ]; then
    echo 1
  else
    echo $(( $1 * $(factorial $(( $1 - 1 ))) ))
  fi
}

# Call the function with the argument
echo "Factorial of 5 is: $(factorial 5)"
EXPLANATION

This Bash script calculates the factorial of a given number using a recursive function called factorial(). The function checks if the input number is equal to zero, if so, it returns 1, indicating the base case of the factorial. Otherwise, it recursively calls itself with decremented values until it reaches the base case. Finally, the script prints the factorial of 5 by invoking the factorial() function with argument 5, displaying the result as “Factorial of 5 is: 120”.

Calculating Factorial Using Recursive Function

Here, the recursive function calculates the factorial of 5.

5. Listing Files in a Directory

The bash function can be used to list all files in a directory. Here’s how to do so:

#!/bin/bash

function list_files() {
  directory=$1
  for file in "$directory"/*; do
    if [ -f "$file" ]; then
      echo "$file"
    fi
  done
}

list_files '/home/ridoy/Downloads' # replace this with your directory
EXPLANATION

This Bash script defines a function named list_files() that takes a directory path as input. It iterates through each file in the specified directory using a for loop and checks if each item is a regular file using the -f conditional expression. If a file is found, its path is echoed to the terminal. Here, the function list_files() is invoked with the directory path ‘/home/ridoy/Downloads’, listing all regular files within that directory.

Listing all Files in a Directory

Here, this script lists all files of the specified directory.

6. Fibonacci Sequence Using Bash Function

A Fibonacci sequence is a series of numbers in which each number is the sum of the two preceding ones. It typically starts with 0 and 1, with subsequent numbers being the sum of the two preceding ones. The sequence goes like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, and so on. Here is how you can implement it in a bash script using a function:

#!/bin/bash

# Define the fibonacci sequence function
fibonacci() {
  a=0
  b=1
  echo "Fibonacci sequence up to $1 terms:"
  for (( i=0; i<$1; i++ )); do
    echo -n "$a "
    echo
    temp=$((a + b))
    a=$b
    b=$temp
  done
}

# Call the function with the argument
fibonacci 12
EXPLANATION

This Bash script generates the Fibonacci sequence up to a specified number of terms using a function named fibonacci(). It initializes variables a and b to 0 and 1, respectively, then iterates through a for loop for the specified number of terms. Within each iteration, it calculates the next Fibonacci number by adding the previous two numbers and updates the variables accordingly. Then it echoes the Fibonacci sequence up to the specified number of terms to the terminal.

generating Fibonacci Sequence Using Bash Function

Here, the script lists the first 12 Fibonacci numbers in the terminal.

7. Check Prime Number

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. In other words, a prime number is only divisible by 1 and itself, and it cannot be formed by multiplying two smaller natural numbers. To check whether a number is prime or not by calling a bash function, execute the following bash script:

#!/bin/bash

# Define the prime number checker function
is_prime() {
  for (( i=2; i<=$1/2; i++ )); do
    if [ $(($1 % $i)) -eq 0 ]; then
      echo "$1 is not a prime number."
      return
    fi
  done
  echo "$1 is a prime number."
}

# Call the function with the argument
is_prime $1
EXPLANATION

This bash script uses a function named “is_prime()” to check whether the user-given number is prime or not, it iterates through a for loop dividing the input number by numbers from 2 to half of the input number. If the input number is divisible by any of these numbers without any remainder, it concludes that the number is not prime and echoes a message indicating it is not prime. And if the loop completes without finding any divisiors it echoes a message confirming that the number is prime.

Check Prime Number using bash function

Here, the bash script tests whether 17 and 51 are prime numbers.

8. File Size Checker

The function can be used to check the size of a file and determine if a file is small, medium, or large compared with a given limit. Here is how to do so in bash scripting using functions and conditional statements:

#!/bin/bash

# Define the file size checker function
check_file_size() {
  local file_size=$(stat -c %s "$1")
  echo "File size is $file_size bytes."
  if [ $file_size -lt 1024 ]; then
    echo "File size is small."
  elif [ $file_size -lt 1048576 ]; then
    echo "File size is medium."
  else
    echo "File size is large."
  fi
}

# Call the function with argument
check_file_size "encryptDecrypt.sh"
EXPLANATION

This bash script defines a function named “check_file_size” to check the size of a specified file and categorizes it as small, medium, or large based on the predefined thresholds. It retrieves the file size using the stat command and stores it in a variable. The script then echoes the file size in bytes and evaluates the size against the thresholds to determine the file’s category.

check file size checker

Here, the bash script checks the size of a file and categorizes it as a medium-sized file.

9. Directory Size Calculator

The du command in Linux is used to estimate file and directory space usage. It stands for “disk usage”. This command recursively calculates the disk usage of directories and subdirectories and lists the total usage for each directory for a given directory. It is a handy tool for checking which files or directories are consuming the most space on a filesystem. In the following example, the du command is used to calculate the size of a directory within a function:

#!/bin/bash

# Define the directory size calculator function
calculate_directory_size() {
  size=$(du -sh "$1" | cut -f1)
  echo "Size of directory $1: $size"
}

# Call the function with the argument
calculate_directory_size '/home/ridoy/Bash Function Examples'
EXPLANATION

This bash script defines a function called “calculate_directory_size” that takes the directory path as an argument, retrieves the size of the directory using the “du” command, and extracts the size information using the cut command. Then it echoes the size of the directory along with its path to the standard output.

check total size of a directory using the du command in bash function

Here, the script calculates the total size of a directory

10. Reverse a String

Reversing a string is an important task in programming and various applications. It is often needed for different text processing and manipulation and text processing tasks or analysis tasks. Here is how to reverse a string in the bash scripting using a function:

#!/bin/bash

# Define the function to reverse a string
reverse_string() {
  local input="$1"
  local reversed_string=""
  local length=${#input}

  # Iterate through the characters of the string in reverse order
  for (( i = length - 1; i >= 0; i-- )); do
    reversed_string="${reversed_string}${input:i:1}"
  done

  # Return the reversed string
  echo "$reversed_string"
}

# Prompt the user to enter a string
read -p "Enter a string: " input_string

# Call the function to reverse the input string
reversed=$(reverse_string "$input_string")

# Display the reversed string
echo "Reversed string: $reversed"
EXPLANATION

This Bash script defines a function “reverse_string”. It takes an input string and calculates its length. Then it iterates through the characters backward, appending them to a new string “reversed_string”. After the function definition, it prompts the user to input a string and then calls the reverse_string function to reverse the input string. Then it echoes the reversed string to the user.

reverse a string using bash function

Here, the bash script reverses the input string.

11. Count the Occurrences of a Character in a String

Counting the occurrences of a character in a string is a fundamental task in string manipulation and text analysis. It involves iterating through each character in the string and comparing it to the target character to be counted. Here is how to achieve that in the bash scripting:

#!/bin/bash

# Define the function to count occurrences of a character in a string
count_occurrences() {
  local input_string="$1"
  local search_char="$2"
  local count=0

  # Loop through each character in the string
  for (( i = 0; i < ${#input_string}; i++ )); do
    # Check if the current character matches the search character
    if [[ "${input_string:i:1}" == "$search_char" ]]; then
      (( count++ ))
    fi
  done

  # Return the count of occurrences
  echo "$count"
}


# Prompt the user to enter a string
read -p "Enter a string: " input_string

# Prompt the user to enter the character to count
read -p "Enter the character to count: " search_char

# Call the function to count occurrences of the character in the string
occurrences=$(count_occurrences "$input_string" "$search_char")

# Display the count of occurrences to the user
echo "Occurrences of '$search_char' in '$input_string': $occurrences"
EXPLANATION

This Bash script defines a function “count_occurrences” that takes the input string and the character to search for. Then it iterates through each character in the string, incrementing the counter when a match is found. After that, it prompts the user to input a string and the character to count. Then the script calls the count_occurrences function and displays the count of occurrences to the user.

Count the Occurrences of a Character in a String

Here, the script calculates the occurrences of the character “r” from the given string.

12. File Encryption & Decryption

The GnuPG (GPG) package refers to the GNU Privacy Guard in Linux, which is a free and open-source implementation of the OpenPGP standard for encrypting and decrypting data. GPG provides cryptographic privacy and authentication for data communication. It is widely used for various security-related tasks, including securing sensitive data, verifying digital signatures, and ensuring the integrity of software distributions. To encrypt and decrypt files using the GPG package execute the bash script below:

#!/bin/bash

# Function to encrypt a file
encrypt_file() {
  local input_file="$1"
  local output_file="$2"
  gpg --symmetric --cipher-algo AES256 --output "$output_file" "$input_file"
}

# Function to decrypt a file
decrypt_file() {
  local input_file="$1"
  local output_file="$2"
  gpg --decrypt --output "$output_file" "$input_file"
}

# Main function
main() {
  # Prompt user for action choice
  read -p "Enter 'e' to encrypt or 'd' to decrypt: " choice

  # Check user choice
  case "$choice" in
    e|E)
      # Prompt user for file to encrypt
      read -p "Enter the file to encrypt: " input_file
      read -p "Enter the name for encrypted file: " output_file
      encrypt_file "$input_file" "$output_file"
      echo "File encrypted successfully."
      ;;
    d|D)
      # Prompt user for file to decrypt
      read -p "Enter the file to decrypt: " input_file
      read -p "Enter the name for decrypted file: " output_file
      decrypt_file "$input_file" "$output_file"
      echo "File decrypted successfully."
      ;;
    *)
      echo "Invalid choice. Please enter 'e' to encrypt or 'd' to decrypt."
      ;;
  esac
}

# Call the main function
main
EXPLANATION

This bash script defines 3 functions to encrypt and decrypt files using the GNU Privacy Guard (GPG) tool. First, it defines encrypt_file and decrypt_file functions which respectively handle encryption and decryption using the AES256 cipher algorithm. Then the main prompts the user to choose between encryption and decryption, reads input and output file names, and executes the appropriate function based on the user’s choice. It may also ask for a key phrase during the process. Make sure to remember that passphrase.

File Encryption & Decryption using bash function

Here, the bash script first encrypts and then decrypts an image file.

13. Bash Print Function Definition

The bash function definition is a set of instructions or commands grouped as a block under a single name. It can be executed as a unit within a Bash script or interactively in the command line. To check the function definition for a command line function execute the first command and to check the definition of a function from a bash script run the second command:

declare -f function_name
awk '/^function_name\(\)/,/^}$/' bash_script.sh
EXPLANATION

The declare -f function_name command displays the definition of the specified function named function_name in the current shell session. And the awk '/^function_name\(\)/,/^}$/' bash_script.sh command searches for the function definition for function function_name in the specified Bash script file “bash_script.sh” and prints the lines from the function’s definition.

Bash Print shell Function Definition

Here, this command echoed the definition of a shell function.

Bash Print Function Definition from bash script

Here, the command echoed the definition of a function from the bash script.

14. Prime Factorization With Bash Help Function

The help function in bash scripting is a user-defined function that provides guidance and instructions on how to use a script or function. It typically displays information about the script’s syntax, available options, usage examples, and other relevant details that the user might need to know. In the following example, a bash script for prime factorization is demonstrated with a basic help function:

#!/bin/bash

# Define the help function
show_help() {
  echo "Usage: $0 [number]"
  echo "Calculate the prime factors of a given number."
  echo "Options:"
  echo "  number       The number for which to find prime factors"
  echo "  -h, --help   Display this help message"
}

# Check if the user requested help
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
  show_help
  exit 0
fi

# Check if the user provided a number as input
if [ -z "$1" ]; then
  echo "Error: Please provide a number."
  echo "Run '$0 --help' for usage instructions."
  exit 1
fi

# Function to find prime factors of a number
prime_factors() {
  number=$1
  divisor=2

  echo "Prime factors of $number are:"

  while [ $number -gt 1 ]; do
    while [ $((number % divisor)) -eq 0 ]; do
      echo -n "$divisor "
      number=$((number / divisor))
    done
      ((divisor++))
  done
  echo
}

# Get the number from the user input
number=$1

# Call the function to find prime factors
prime_factors $number
EXPLANATION

This bash script is designed to find the prime factors of a given number. It includes a help function that provides usage instructions and options for the script. The help function displays information about how to use the script including the syntax and available options. When the user runs the script with the “-h/–help” option the help function is invoked and prints out the usage instructions.

Prime Factorization With Bash Help Function

Here, this bash script demonstrates how to use the help function.

15. Bash Empty Function

An empty function in bash scripting refers to a function definition that does not contain any commands or statements within its body. Essentially, it is a function declaration without any executable code inside. It serves as a placeholder for functions that may not have any operations to perform but still need to be defined within the script structure. The following is a basic syntax for an empty function:

empty_function() {
    :
}
empty_function(){ :; }
EXPLANATION

The empty function in bash scripting is defined using the colon : built-in null command, which effectively does nothing. It can also be defined as a single-liner function using empty_function(){ :; }.

Bash Empty Function

Here is how to create and call an empty function.

16. Bash Unset Function

The unset command in bash is used to unset or delete variables and functions. When applied to a function, the unset command removes the function definition from the shell’s environment, effectively deleting the function. This function is particularly useful when you want to remove a function definition that is no longer needed or if you want to redefine a function with a new implementation. The basic syntax for the unset command to remove a shell function is as follows:

unset -f function_name
EXPLANATION

The unset -f function_name command removes the definition of the specified function named function_name from the current shell session. It unsets or deletes the function, making it no longer available for use within the script or the shell session.

Bash Unset Function

Here, the unset command removed a function.

Practice Tasks on the Bash Function

If you aim to be better at using the Bash function, then you can try creating a Bash script for the following problems using the Bash function:

  1. Create a Bash function that calculates the area of a rectangle given its length and width. Print the result.
  2. Write a Bash function that checks if a given number is even or odd. Then, print whether the number is even or odd.
  3. Develop a Bash script that checks whether a user-given string is a palindrome. Then, print whether the string is a palindrome or not.
  4. Develop a Bash script that calculates the sum of digits in a given number. Prompt the user to input the number and print the sum of its digits.
  5. Implement a Bash script that converts a temperature from Celsius to Fahrenheit. Prompt the user to input the temperature in Celsius and print the result in Fahrenheit.
  6. Create a Bash script that acts as a simple calculator. Prompt the user to input two numbers and an operation (+, -, *, /). Then operate and print the result.
  7. Design a Bash function that generates a random password of a user-given length. Print the generated password.

Conclusion

In summary, the bash opens a gateway to efficient scripting and automation in the Linux environment. Whether you are a newbie or a Linux pro user, I hope this article will help you in your efficient Linux journey.

People Also Ask

Can you write a function in Bash?

Yes, you can write functions in Bash. Bash functions are blocks of code that perform a specific task and can be reused throughout a script. To define a function, you use the function keyword followed by the function name and parentheses. Within the function, you write the commands or operations you want it to perform. Once defined, you can call the function by its name anywhere in your Bash script.

How do you call a function in Bash?

In Bash, you call a function by simply typing its name followed by parentheses. And if the function takes arguments, you provide them within the parentheses separated by spaces. Though parentheses are not mandatory, and omitting them is a common practice. For example, if you have a function named my_function and you want to call it without any arguments, you write my_function. If it requires arguments, you include them after the function name, like this: my_function arg1 arg2.

What is a function in the bash script?

In a bash script, a function is a block of code that performs a specific task or set of tasks. It encapsulates a series of commands and statements, allowing them to be executed as a single unit. Functions help organize code, improve readability, and enable code reuse by defining logical sections within a script. They can accept input arguments, process data, and return results, enhancing the flexibility and modularity of bash scripts.

Does Bash have a main function?

No, unlike languages like C or Java, in bash scripting there is no explicit main function required for script execution. Instead, Bash scripts start executing from the first line and proceed sequentially until the end of the file unless specified otherwise. Each line or block of code in a Bash script is interpreted and executed in the order it appears, making the concept of a main function unnecessary in Bash scripts.

How do I exit a bash script?

To exit a Bash script, you can use the exit command followed by an optional exit status. Simply include exit in your script to terminate its execution. Optionally, you can specify an exit status ranging from 0 to 255, where 0 indicates successful execution and any other value indicates an error or abnormal termination.

Related Articles


<< Go Back to Bash Functions | Bash Scripting Tutorial

5/5 - (11 votes)
Ridoy Chandra Shil

Hello everyone. I am Ridoy Chandra Shil, currently working as a Linux Content Developer Executive at SOFTEKO. I am a Biomedical Engineering graduate from Bangladesh University of Engineering and Technology. I am a science and tech enthusiast. In my free time, I read articles about new tech and watch documentaries on science-related topics. I am also a big fan of “The Big Bang Theory”. Read Full Bio

Leave a Comment