How to Use “if” Statement in Bash Function [7 Examples]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

The combination of the “if” conditional statement and functions in bash scripting enhances the script’s flexibility and modularity. When used together the “if” statement enables conditional execution of code blocks based on certain criteria while functions encapsulate specific tasks or operations into reusable blocks of code. By integrating the two bash scripts becomes more organized and easier to maintain. This article will dive into how to incorporate the if conditional statement with function in bash scripting.

What is the “if” Statement in the Bash Function?

The if statement in bash is a control structure that allows the execution of certain code blocks based on the evaluation of conditions. It evaluates whether a given condition is true or false and executes specific code accordingly. A function in bash is a set of commands grouped together to perform a specific task. It encapsulates a series of instructions that can be executed multiple times within a script.

In bash scripting the “if” statement and functions can be combined to create more structured and modular scripts. Functions can contain the “if” statements to perform conditional operations within the context of the function’s task. Here is the basic syntax of the if conditional syntax within the function:

function function_name {
  # Function body

  if [ condition ]; then
    # Code to be executed if the condition is true
  else
    # Code to be executed if the condition is false
  fi

  # Other function code
}
EXPLANATION

This basic syntax defines a bash function named “function_name” with a body containing various commands. Within the function, an “if” statement evaluates a specified condition. If the condition is true the corresponding code block executes otherwise the code block within the “else” statement executes.

7 Examples of Using “if” Within Function in Bash

The if conditional statement and function hold paramount importance in bash scripting as they introduce modular decision-making capabilities into scripts. These allow the bash script to dynamically adapt its behavior, enabling it to handle various scenarios and user inputs effectively. From checking numbers for odd or even properties to verifying file existence and assessing network connectivity, this article will cover some of those practical examples.

1. Check if a Number is Even or Odd

Checking if a number is odd or even is a fundamental task in programming that aids in various computations and logical operations. In many algorithms and applications such as sorting algorithms, statistical analysis, game development, data validation, and conditional execution knowing the parity of a number helps in making decisions or performing specific operations.

The following script checks whether a number is even or odd using the if conditional statement and function:

#!/bin/bash

check_even_odd() {
  if [ $(($1 % 2)) -eq 0 ]; then
    echo "$1 is even."
  else
    echo "$1 is odd."
  fi
}

# Test the function
check_even_odd 10
check_even_odd 7
EXPLANATION

This Bash script defines a function named check_even_odd that takes a single argument $1, representing a number. Inside the function, an if statement evaluates whether the number modulo 2 is equal to 0, indicating that it is even. If the condition is true, the script echoes that the number is even; otherwise, it echoes that the number is odd.

To test the function, two calls are made: check_even_odd 10 and check_even_odd 7, which respectively determine whether 10 and 7 are even or odd using the defined function and conditional logic.

Check if a Number is Even or Odd using bash if conditional statement within function

After running the script, it shows that the given number 10 is even and 7 is odd.

2. Check if a File Exists

Validating if a file exists in bash programming ensures that scripts handle valid file paths and prevent errors during file operations. It enables conditional execution, allowing scripts to alter their behavior based on specific files. Here is how to check a file’s existence using an if statement with the bash function:

#!/bin/bash

check_file_exists() {
  if [ -e "$1" ]; then
    echo "$1 exists."
  else
    echo "$1 does not exist."
  fi
}

# Test the function
check_file_exists "Backup.sh"
check_file_exists "nonexistent_file.txt"
EXPLANATION

This Bash script defines a function named check_file_exists designed to verify the existence of a file specified as an argument. Within the function, an if statement checks if the file exists using the -e flag. If the file exists, the script echoes a message indicating its existence; otherwise, it indicates that the file does not exist.

To test the functionality, the script makes two function calls: check_file_exists "Backup.sh" to verify the existence of a file named “Backup.sh”, and check_file_exists "nonexistent_file.txt" to check for a file named “nonexistent_file.txt”.

Check if a file exists using bash if conditional statement within function

Here, the bash script checks if the given file exists or not.

3. Check if a Directory is Empty

Verifying if a directory is empty in Bash programming facilitates effective directory management and automation. It allows scripts to determine whether a directory contains any files or subdirectories before performing operations like deletion, copying, or moving. This helps prevent any unintended data loss or errors by ensuring that directories are manipulated safely based on their content.

To check whether a directory is empty or not using Bash if function, execute the following bash script:

#!/bin/bash

check_directory_empty() {
  if [ -z "$(ls -A $1)" ]; then
    echo "$1 is empty."
  else
    echo "$1 is not empty."
  fi
}

# Test the function
check_directory_empty "/home/ridoy/Downloads"
check_directory_empty "/home/ridoy/Downloads/empty"
EXPLANATION

The provided Bash script defines a function named check_directory_empty, which determines whether a specified directory is empty or not. Within the function, an if statement employs the -z flag to evaluate the output of the ls -A command, which lists the contents of the directory. If the directory is empty, the script echoes a message indicating that it is empty; otherwise, it confirms that the directory is not empty.

To test the function, the script executes two function calls: check_directory_empty "/home/ridoy/Downloads/empty" to verify if an empty directory exists at the specified path and check_directory_empty "/home/ridoy/Downloads" to assess a directory containing files.

Check whether a directory is empty using bash if conditional statement within function

Here the script checks whether the given directory is empty or not.

4. Network Connectivity Checker

Checking network connectivity in Linux is essential to ensure communication with other devices and services. It helps diagnose and troubleshoot network issues promptly. Additionally, it ensures the reliability and functionality of automated tasks and scripts dependent on network services. Execute the following code to do so in bash scripting:

#!/bin/bash

check_connectivity() {
  ping -c 1 google.com &> /dev/null
  if [ $? -eq 0 ]; then
    echo "Internet connection is active."
  else
    echo "No internet connection."
  fi
}

# Test the function
check_connectivity
EXPLANATION

The Bash script defines the check_connectivity function which initiates a single ping request to google.com using the ping command, with output redirection to /dev/null to suppress display messages. It then evaluates the exit status of the ping command: if the exit status is 0 (indicating successful completion), the script echoes “Internet connection is active”; otherwise, it indicates “No internet connection.”

Check network connectivity using bash if conditional statement within function

Here the script checks the internet connectivity of the user.

5. File Backup Function with Timestamp

Creating file backups in Linux is crucial for data protection and disaster recovery. It safeguards against accidental deletion, corruption, or system failures. Also, backups provide a means to restore data to its previous state, ensuring business continuity and minimizing data loss in case of emergencies.

Here is how to create backup of a file with the timestamp using function and if conditional statement in bash:

#!/bin/bash

backup_file() {
  if [ -f "$1" ]; then
    timestamp=$(date +"%Y%m%d%H%M%S")
    backup_name="$1_$timestamp.backup"
    cp "$1" "$backup_name"
    echo "Backup of $1 created as $backup_name"
  else
    echo "$1 does not exist."
  fi
}

# Test the function
backup_file "Connectivity.sh"
backup_file "nonexistent_file.txt"
EXPLANATION

This Bash script defines a function backup_file. It creates a backup of a specified file with a timestamp appended to its name. Upon invocation, the function checks if the file exists using the -f condition. If the file exists, it generates a timestamp using the date command with a specific format. Then, it constructs a backup name by appending the timestamp to the original filename and the extension “.backup”.

Subsequently, the script copies the original file to the backup name using the cp command and displays a message confirming the backup creation. If the specified file does not exist, the script notifies the user accordingly. Invoking the function requires two tests: once with an existing file “Connectivity.sh” and once with a non-existent file “nonexistent_file.txt”.

create backup of a file

Here, the bash script creates a backup of the given file automatically with a timestamp.

6. Grade Calculator Function

A grade calculator is valuable for automating the grading process in educational or evaluation systems. It saves time for instructors or administrators by simplifying the task of assigning grades based on predefined criteria. It also ensures consistency and accuracy in grading.

To implement a basic grade calculator using the if conditional statement and function, execute the following bash script:

#!/bin/bash

calculate_grade() {
  if [ "$1" -ge 90 ]; then
    echo "A"
  elif [ "$1" -ge 80 ]; then
    echo "B"
  elif [ "$1" -ge 70 ]; then
    echo "C"
  elif [ "$1" -ge 60 ]; then
    echo "D"
  else
    echo "F"
  fi
}

# Test the function
echo "Grade for 95: $(calculate_grade 95)"
echo "Grade for 75: $(calculate_grade 75)"
echo "Grade for 50: $(calculate_grade 50)"
EXPLANATION

This script defines a function named calculate_grade. It calculates the letter grade based on the numerical score passed as an argument. The function uses a series of if-elif-else conditional statements to determine the appropriate grade based on the score range. To test the function, several scores are passed as arguments, and the corresponding grades are displayed using the echo command with the calculate_grade function calls.

grade automatically based on input number

Here, the bash script calculates and determines the grade automatically.

7. Temperature Converter

Conversion of temperature between Celsius and Fahrenheit scales is important for various applications such as weather forecasting, cooking, and scientific experiments. It enhances convenience by providing quick and accurate temperature conversions without the need for manual calculations.

The following bash script can automatically convert temperature between these two scales using the if statement in the function:

#!/bin/bash

convert_temperature() {
  if [ "$2" == "C" ]; then
    result=$(echo "scale=2; ($1 - 32) * 5 / 9" | bc)
    echo "$1°F is $result°C"
  elif [ "$2" == "F" ]; then
    result=$(echo "scale=2; ($1 * 9 / 5) + 32" | bc)
    echo "$1°C is $result°F"
  else
    echo "Invalid temperature scale."
  fi
}

# Test the function
convert_temperature 32 F
convert_temperature 100 C
EXPLANATION

This script defines a function named convert_temperature that converts temperatures between Celsius (°C) and Fahrenheit (°F) scales. It checks the second argument passed to the function to determine the scale of the input temperature. When the temperature is in Celsius, it converts to Fahrenheit using the formula (°C * 9 / 5) + 32. If the temperature is in Fahrenheit, it converts to Celsius using the formula (°F – 32) * 5 / 9.

The bc command is used for floating-point arithmetic within the script. The function is then tested by calling it with specific temperature values and scales, and the converted temperatures are displayed accordingly.

convert temperature between Celsius (°C) and Fahrenheit (°F) scales

Here, the script converts the Celsius temperature to Fahrenheit and the Fahrenheit temperature to the Celsius temperature.

Practice Tasks on the Bash “if” Function

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

  1. Write a function is_positive that takes a number as an argument and checks whether that number is positive, negative, or zero. Use an if statement within the function to check the condition.
  2. Write a function is_leap_year that takes a year as an argument and checks if it is a leap year or not.
  3. Write a bash function that takes a directory name as input and prints whether it’s writable by the current user.
  4. Write a bash function that takes a string as input and prints whether it’s a palindrome.
  5. Develop a bash function that takes a password as input and checks its strength (e.g., length, presence of special characters).

Conclusion

In summary, the if conditional statement and function stand as a cornerstone of the bash scripting offering users a powerful mechanism for implementing decision-making logic with modularity. Whether you are a novice or a scripting expert I hope this article helps you understand the core principles and usage of the if conditional statements within function in bash scripting.

People Also Ask

How to use the if function in Bash?

To use the if function in Bash, start with the keyword if, followed by the condition you want to evaluate, and then specify the commands to execute if the condition is true. If the condition is not met, an optional else statement can be used to define alternative commands to execute. Additionally, you can include multiple conditions using elif (else if) statements for more complex logic. Finally, end the if function block with fi to mark its closure.

What does == mean in Bash?

In Bash, the == operator is used for string comparison within conditional statements, such as if statements. It checks if two strings are equal. When using the == operator, Bash evaluates whether the strings on both sides of the operator are identical. If they are, the condition is considered true, allowing the associated code block to be executed. However, if the strings are not equal, the condition is false, and the execution moves to the next statement or block of code. This operator is crucial for implementing logic and decision-making in Bash scripts.

How to use two if statements in Bash?

To use two if statements in Bash, you can employ a nested structure, where one if statement is contained within another. Begin by writing the first if statement, followed by a block of code to execute if the condition is true. Inside this block, insert a second if statement with its own condition and corresponding code block. Ensure proper indentation for clarity and readability. Finally, close each if statement with the fi keyword to denote the end of the block.

What is ++ I in bash?

In Bash scripting, the ++ is an operator used for incrementing the value of a variable by 1. When ++ is placed before a variable, it represents the pre-increment operator, which increments the value of the variable before it is used in an expression. This means that the value of the variable is incremented and then the new value is assigned or used in the expression.

What is $1 in the bash script?

In a bash script, $1 represents the first argument passed to the script or function when it is invoked. It is a positional parameter that holds the value of the first argument supplied on the command line. Using $1 allows scripts and functions to access and manipulate the value of the first argument dynamically during execution. Additionally, $1 can be used in conjunction with other positional parameters like $2, $3, and so on, to handle multiple arguments passed to the script or function.

What is $$ in shell?

In shell scripting, $$ represents the process ID (PID) of the currently running shell or script. It is a special variable that holds the unique identifier assigned to the shell process by the operating system. The $$ variable is commonly used in shell scripts to generate temporary files with unique names, manage process-related tasks such as logging, or create directories with distinct identifiers. By incorporating $$ into scripts, developers can ensure that their shell processes are uniquely identified and avoid conflicts or overwrites when multiple instances of the script are running concurrently.

Related Articles


<< Go Back to Bash Function Examples | Bash Functions | Bash Scripting Tutorial

Rate this post
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