Exploring Bash — Part 3

Dineshkumaar R
6 min readApr 8, 2024

--

Introduction

Hey Friends, Welcome back to my Bash exploration blog series! In this installment, we’ll master conditional statements like ‘if’ and ‘case’, along with Boolean operations, to elevate your Bash scripting prowess. Stay tuned for insights and tips to become a Bash scripting ninja. Let’s dive in!

If Statements

In Bash scripting, conditional statements are used to make decisions based on certain conditions. The ‘if’ statement allows you to execute a block of code if a specified condition is true. You can also include ‘elif’ (short for “else if”) and ‘else’ clauses to handle multiple conditions.

Syntax of statement:

if condition
then
# code to execute if condition is true
elif another_condition
then
# code to execute if another_condition is true
else
# code to execute if all conditions are false
fi

Example 1:

age=20
if [ $age -ge 18 ]
then
echo "You are an adult."
else
echo "You are a minor."
fi

This Bash script evaluates the variable ‘age’, determining if it’s greater than or equal to 18. If true, it echoes “You are an adult.”; otherwise, it echoes “You are a minor.”

Example 2:

#!/bin/bash

# Example code to determine the time of the day

hour=$(date +"%H")

if [ $hour -lt 12 ]; then
echo "Good morning!"
elif [ $hour -lt 18 ]; then
echo "Good afternoon!"
else
echo "Good evening!"
fi

• We obtain the current hour using the date command and store it in the hour variable.
• The if, elif, and else statements are used to execute different code blocks based on the value of hour.
• If the hour is less than 12, it prints “Good morning!”.
• If the hour is between 12 and 17 (inclusive), it prints “Good afternoon!”.
• If the hour is 18 or greater, it prints “Good evening!”.
• The script ends with fi, marking the end of the conditional structure.

Case Statements

The ‘case’ statement is useful when you need to evaluate multiple conditions in a more concise and readable manner. It allows you to match a value against a list of patterns and execute code based on the first matching pattern.

Syntax of Case Statement

case expression in
pattern1)
# code to execute if expression matches pattern1
;;
pattern2)
# code to execute if expression matches pattern2
;;
*)
# code to execute if no patterns match
;;
esac

Example 1:

# Example code using case statement to determine input type

read -p "Enter something: " input

case $input in
[0-9]*)
echo "You entered a number."
;;
[a-zA-Z]*)
echo "You entered a word."
;;
*)
echo "You entered something else."
;;
esac

• We prompt the user to enter something.
• The case statement checks the value of input.
• [0–9]* matches if the input starts with a number.
• [a-zA-Z]* matches if the input starts with a letter (uppercase or lowercase).
• If the input matches one of these patterns, it prints the corresponding message.
• If the input doesn’t match any of the specified cases, it prints “You entered something else.”

Example 2:

# Example code using case statement to determine day of the week

echo -n "Enter a day of the week: "
read day

case $day in
"Monday" | "monday" | "Mon" | "mon")
echo "It's Monday."
;;
"Tuesday" | "tuesday" | "Tue" | "tue")
echo "It's Tuesday."
;;
"Wednesday" | "wednesday" | "Wed" | "wed")
echo "It's Wednesday."
;;
"Thursday" | "thursday" | "Thu" | "thu")
echo "It's Thursday."
;;
"Friday" | "friday" | "Fri" | "fri")
echo "It's Friday."
;;
"Saturday" | "saturday" | "Sat" | "sat")
echo "It's Saturday."
;;
"Sunday" | "sunday" | "Sun" | "sun")
echo "It's Sunday."
;;
*)
echo "Invalid input. Please enter a valid day of the week."
;;
esac

• We prompt the user to enter a day of the week.
• The case statement checks the value of day.
• We use pattern matching with | to match multiple variations of each day (e.g., “Monday”, “monday”, “Mon”, “mon”).
• Depending on the input, it prints the corresponding day of the week.
• If the input doesn’t match any of the specified cases, it prints “Invalid input. Please enter a valid day of the week.”

Boolean Operations

In Bash, you can use Boolean operators (‘&&’ for logical AND, ‘||’ for logical OR, ‘!’ for logical NOT) to combine or negate conditions in conditional statements.

Example:

age=20
if [ $age -ge 18 ] && [ $age -le 60 ]
then
echo "You are of working age."
fi

• age=20: Assigns the value 20 to the variable age.
• if [ $age -ge 18 ] && [ $age -le 60 ]: Begins the conditional statement. Checks if age is greater than or equal to 18 and less than or equal to 60 using the -ge (greater than or equal to) and -le (less than or equal to) operators respectively. The && operator performs a logical AND operation, meaning both conditions must be true for the code block to execute.
• then: Indicates the beginning of the code block to execute if the condition is true.
• echo “You are of working age.”: Prints “You are of working age.” to the terminal if the condition is true.
• fi: Marks the end of the conditional statement.

Conditional Execution

Conditional execution operators (‘;’ , ‘&&’ , ‘||’) allow you to control command execution based on the success or failure of previous commands. ‘;’ is used to separate multiple commands, ‘&&’ executes the next command only if the previous one succeeds, and ‘||’ executes the next command only if the previous one fails.

Example 1:

mkdir my_directory && cd my_directory || echo "Failed to create or change directory."

The command mkdir my_directory && cd my_directory || echo “Failed to change directory.” attempts to create a directory named “my_directory”, then changes into that directory if the creation is successful. If the directory creation or changing fails, it prints “Failed to change directory.” to the terminal.

Example 2:

# Example of conditional execution
# If file exists, display its content. Otherwise, print a message.

[ -f "example.txt" ] && cat example.txt || echo "File not found."

When writing conditional statements, it’s essential to maintain readability and efficiency. Using clear and descriptive variable names, as well as organizing code logically, can improve the maintainability of your scripts. Additionally, minimizing the number of nested conditions and utilizing appropriate boolean operations can make your conditional statements more concise and efficient.

Summary of the blog

• The blog explores Bash scripting with a focus on conditional statements like ‘if’ and ‘case’.
• ‘if’ statements allow executing code blocks based on specified conditions, with examples provided for age and time-based conditions.
• ‘case’ statements offer a concise way to handle multiple conditions, demonstrated with examples for input types and days of the week.
• Boolean operations like ‘&&’, ‘||’, and ‘!’ are introduced for combining or negating conditions.
• Conditional execution operators (‘;’, ‘&&’, ‘||’) are discussed to control command execution based on the success or failure of previous commands.

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

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)