Understanding Bash If Else and other Conditional Statements

Published:23 October 2023 - 9 min. read

Azure Cloud Labs: these FREE, on‑demand Azure Cloud Labs will get you into a real‑world environment and account, walking you through step‑by‑step how to best protect, secure, and recover Azure data.

Writing a Bourne Again Shell (Bash) script can be a rewarding experience, especially when you add logic to it, ensuring its robustness. One way to incorporate this logic, making your script smarter, is through the use of conditional statements, specifically ‘bash if else’.

In this deep dive, you’re about to grasp the power and nuances of the Bash if-else and case statements. This will aid you in crafting error-free, intelligent Bash scripts. We’ll also sprinkle in some best practices to ensure you’re scripting like a pro.

Excited? Delve in, and elevate your Bash scripting acumen!

Setting the Stage: Prerequisites

To make the most of this tutorial, there are some essentials you should have in place:

  • A Linux or Windows system armed with Bash. For those on Windows, the Windows Subsystem for Linux (WSL) is your best bet.
  • A code/text editor to write and refine your ‘bash if else’ scripts.

Why Should You Leverage bash if else Statements?

Why are conditional statements so revered in Bash scripting? Simply put, they endow your scripts with decision-making capabilities based on predefined conditions.

For instance, you can employ ‘bash if else’ to verify if a file exists prior to attempting its deletion. Alternatively, you might want to see if a user holds the requisite permissions before letting them access a resource.

Infusing scripts with ‘bash if else’ structures not only amplifies their flexibility but also their potency. Envision a script designed to purge all files in a folder. Using ‘bash if else’, you can surgically delete only those files aged over 30 days, preserving the rest.

Diving into the ‘bash if else’ Statement

Now, let’s leave the introduction behind and get our hands dirty. We’ll begin with one of the most universally embraced conditional statements: the ‘bash if else’ statement.

At its heart, the ‘bash if else’ is a gateway to insert conditionals into your Bash scripts. Observe its elegant syntax below:

  • It starts with the if keyword, succeeded by the conditions encapsulated within [[ ]]. Following this, the code residing inside the ‘bash if else’ statement is executed, concluding with the fi keyword.
  • The then keyword segregates the condition from the actions (or statements) that execute when the conditions are satisfied. This action block can span multiple lines, separated by semicolons (;).
if [[ condition ]]; then

Imagine scripting a login system. It prompts for the correct username before granting access:

1. Launch your terminal and initiate a new bash_if_demo.sh file utilizing your preferred text editor. This will be our playground to understand ‘bash if else’ statements.

nano bash_if_demo.sh

2. Embed the ‘bash if else’ example provided below into your bash_if_demo.sh file. Once inserted, save the modifications and exit the editor.

The sample ‘bash if else’ script prompts for a username. If the expected username is entered, a welcoming message gets displayed, supplemented by the current date and time.

Maintaining a record of the date and time of user access attempts can be invaluable for future analyses.

The introductory line #!/bin/bash (commonly known as shebang) directs the system regarding the interpreter to employ for processing the subsequent code in the script. Here, ‘bash’ is our chosen interpreter.

# Prints a question to the screen.
echo "Whats your name?"
# Captures keyboard input, storing it in the $NAME variable
read NAME
# Kicks off the 'bash if else' statement - examines if the value in $NAME 
# aligns with "ATA". If there's a match, the enclosed code is executed. If not, it's skipped.
if [ $NAME == "ATA" ]
  # Displays a message only if the value in $NAME equals "ATA".
  echo "Welcome back ATA!"
# Outside the 'bash if else', this always showcases the present date and time.

3. Now, let’s put our ‘bash if else’ script to the test. Execute the command below:

bash bash_if_demo.sh

Remember, regardless of the Bash shell variant you’re employing, prefix your script name with ‘bash’. This ensures the system harnesses Bash for script execution.

Enter “ATA” and hit Enter. The outcome should resemble the following:

bash if else in action - Executing the bash_if_demo.sh Script
Demonstration of the bash_if_demo.sh ‘bash if else’ Script

If you input anything other than “ATA,” the welcome message will be absent from the output. Only the current date and time will be showcased. This behavior is credited to the ‘bash if else’ statement which checks for a precise match with the value in the $NAME variable.

Do note that ‘bash if else’ statements are case sensitive. Hence, “ata,” “aTa,” “Ata,” and so forth, are distinct from “ATA.”

bash if else demonstration - Entering Incorrect Value
Outcome on Entering a Non-matching Value

Consistently test your ‘bash if else’ scripts with varied inputs. This ensures that the scripts operate as anticipated.

Digging Deeper: Nested ‘bash if else’ Statements

You’ve already grasped the rudiments of crafting ‘bash if else’ statements. While this foundational knowledge suffices for straightforward tasks, intricate scripts often demand advanced constructs. This is where nested ‘bash if else’ statements come into play. Essentially, it’s an ‘if’ statement housing one or several additional ‘if’ statements.

The structure below illustrates the basic syntax for nested ‘bash if else’ statements. Here, the outer if [[ conditions ]] clause encompasses code executable only upon condition fulfillment. In our context, the nested code is another ‘if’ statement.

  • if [[ conditions ]] – This represents the external ‘bash if else’ statement. The nested code (another ‘if’ statement) only gets executed if the stated condition holds true.
  • if [[ condition2 ]] – This represents the internal ‘bash if else’ clause. It holds code that gets executed if and only if both conditions are satisfied.
if [[ conditions ]]; then
	if [[ condition2 ]]; then

Let’s delve deeper. Enhancing our previous ‘bash if else’ example, we’ll now include an if statement that inquires about a password:

1. First, establish a new file titled bash_nested_if_demo.sh using your favorite text editor.

nano bash_nested_if_demo.sh

2. Transfer the ‘bash if else’ code provided below into the bash_nested_if_demo.sh file, save your changes, and close the editor.

This ‘bash if else’ code prompts for both a name and a password. Should the conditions for the name and password align, a particular message gets displayed. If there’s no match, the output only displays the current date and time.

# Puts forth a message prompting for a username.
echo "Whats your name?"
# Gathers user input.
read NAME
# Commences the 'bash if else' statement to verify if $NAME matches "ATA."
if [ $NAME == "ATA" ]
 # Poses a subsequent question, this time for a password.
 echo "Password?"
 # Captures the password input.
 read Password
   # Nested 'bash if else' - Ascertains if the $Password corresponds with "pwd123."
   if [ "$Password" == "pwd123" ]; then
     # Displays a message if both conditions regarding name and password are met.
     echo "You've successfully logged in as ATA."
# Highlights the present date and time.

3. Now, let’s see this ‘bash if else’ script in action. Run the command below:

bash bash_nested_if_demo.sh

For optimal results, input ATA as the username and pwd123 as the password.

bash if else demonstration - Executing the bash_nested_if_demo.sh Script
Demonstrating the bash_nested_if_demo.sh Script in action

If your inputs deviate from “ATA” or “pwd123”, the only feedback you’ll receive pertains to the current date and time. This is because the ‘bash if else’ structure necessitates fulfilling both conditions.

bash if else validation - Verifying entered conditions
Validating if entered conditions are met using ‘bash if else’

Decoding ‘Bash If Else’ Statements

‘Bash if else’ statements are cornerstones in Bash scripting, providing decisive capabilities to your scripts. However, it’s pivotal to understand that using ‘if’ statements isn’t without its downsides.

The glaring challenge is that excessive reliance on ‘if’ can clutter your code, making it tedious and challenging, especially when multiple nested ‘if’ statements come into play. Such scripts risk becoming “spaghetti code”, characterized by reduced readability and increased complexity.

So, how do you streamline your ‘bash if else’ script to remain comprehensible? Opt for ‘if else’ statements over a heap of nested ‘if’ ones. The ‘else’ keyword offers the convenience of specifying a code chunk to execute if the ‘if’ condition remains unmet.

For a clearer perspective, consider the syntax for ‘Bash If Else’ below, where:

  • if [[ conditions ]] – Here, the ‘bash if else’ statement includes the code (statement1) that triggers only when the stated condition is valid.
  • else – This is part of the ‘bash if else’ structure. The else statement encompasses the code (statement2) that gets executed when the condition in the preceding if clause isn’t satisfied.
if [[ conditions ]]; then

Imagine crafting a simple ‘bash if else’ game where the system expects a random number from the user:

1. Start by constructing a new file named bash_if_else_demo.sh.

nano bash_if_else_demo.sh

2. Integrate the subsequent ‘bash if else’ code into your bash_if_else_demo.sh file, save the alterations, and then exit.

The underlying ‘bash if else’ code prompts the user for their lucky number. If the input is even, it displays the ‘You Won!’ message. Contrarily, an odd number triggers the ‘You Lost!’ output.

# Broadcasts a request for the user's lucky digit
echo -n "Input Your Lucky Number:"
# Accepts the number entered.
read var
# 'bash if else' condition to ascertain if the value is even.
if [ $((var%2)) == 0 ]; then
 # Announces a win if the condition is met
 echo "You Won with 'bash if else'!"
 # Announces a loss if the condition isn't met
 echo "You Lost using 'bash if else'!"

3. To witness the ‘bash if else’ script in operation, run the command below:

bash bash_if_else_demo.sh

Upon entering an even digit, you should see the “You Won with ‘bash if else’!” message. Conversely, inputting an odd digit should yield the “You Lost using ‘bash if else’!” feedback.

'bash if else' game demonstration - Run the bash_if_else_demo.sh Script
Run the ‘bash if else’ game, bash_if_else_demo.sh Script

To enrich the ‘bash if else’ script, consider incorporating a segment that determines if the user inputs a letter or a distinct character as opposed to a number.

Decoding ‘Bash If Else’ and Case Statements

By this juncture, you’ve explored a couple of methods to forge decisions in your Bash scripts, namely ‘bash if else’ statements. But Bash offers another avenue for decision-making – the case statement.

Akin to the ‘bash if else’, the case statement is adept at stipulating code sequences to be executed based on specified conditions. A notable advantage with the case statement is its sheer conciseness and clarity, especially when juxtaposed against nested ‘bash if else’ scenarios.

To fully grasp the ‘bash if else’ alternative, let’s delve into the syntax of the case statement:

  • case $VAR in – This segment of the case construct evaluates the $VAR variable against defined patterns until a match surfaces.
  • pattern1) and pattern2) – These are the criterion to test against, and once a match is detected, the corresponding code (statement1 or statement2) springs into action.
  • esac – Concludes the case structure.
case $VAR in

Imagine you’re designing a ‘bash if else’ script where users input their country names, and in response, the script displays the predominant language of that country.

1. Begin by generating a file named bash_case_demo.sh.

nano bash_case_demo.sh

2. Incorporate the ‘bash if else’ code provided below into your bash_case_demo.sh file, then save and exit.

The ensuing ‘bash if else’ script will prompt the user for their country’s name and, based on the ‘case’ patterns, print the primary language spoken in the mentioned country.

# Probes the user with a query about their country of residence
echo -n "In which country do you reside?"
# Captures the user's response.
read var
# Reveals the standard language in the user's selected country ($var),
# relying on the patterns within the 'case' framework.
echo -n "The official language of $var is "

# The 'bash if else' case statement evaluates if the user's input ($var) aligns with the patterns.
case $var in
# Establish patterns that unveil the primary language of the user's chosen country.
  echo -n "English"

  echo -n "English and French"

 Algeria | Bahrain | Egypt| Jordan)
  echo -n "Arabic"

  echo -n "unknown"

3. To experience this ‘bash if else’ script firsthand, employ the subsequent command:

bash bash_case_demo.sh

You’ll discern that the script accurately highlights the language in accordance with the user’s chosen country.

If the provided country doesn’t correspond with the stipulated patterns, the default (*) pattern gets triggered, resulting in the output “unknown.”

bash if else demonstration - Running the bash_case_demo.sh Script
Illustrating the functionality of the bash_case_demo.sh Script

Wrapping Up Bash Conditional Statements

In this guide, you’ve embarked on the journey of understanding ‘bash if else’ and other conditional statements in Bash. From the simple ‘if’ statement to the intricate ‘if-else’ and ‘case’ statements, you’re now equipped with essential tools for effective Bash scripting.

With these ‘bash if else’ fundamentals under your belt, you can construct Bash scripts more proficiently, reducing the margin for errors.

But remember, this is merely the tip of the iceberg. Bash offers a vast array of conditional statements. Perhaps, consider delving into the Bash elif statement and &&, OR and || operators for deeper insights. With dedication, mastering Bash scripting will soon be within reach!

Hate ads? Want to support the writer? Get many of our tutorials packaged as an ATA Guidebook.

Explore ATA Guidebooks

Looks like you're offline!