Start Coding

Topics

Bash if-else Statements

If-else statements in Bash are fundamental control structures that allow you to make decisions in your shell scripts. They enable your script to execute different code blocks based on specified conditions.

Basic Syntax

The basic syntax of an if-else statement in Bash is as follows:

if [ condition ]
then
    # Code to execute if condition is true
else
    # Code to execute if condition is false
fi

The fi keyword marks the end of the if-else block, which is "if" spelled backwards.

Simple Example

Here's a simple example that checks if a number is positive:

#!/bin/bash

number=10

if [ $number -gt 0 ]
then
    echo "The number is positive"
else
    echo "The number is not positive"
fi

Conditional Operators

Bash uses various operators for comparisons in if statements:

  • -eq: Equal to
  • -ne: Not equal to
  • -gt: Greater than
  • -lt: Less than
  • -ge: Greater than or equal to
  • -le: Less than or equal to

Multiple Conditions

You can use elif (else if) to check multiple conditions:

#!/bin/bash

age=25

if [ $age -lt 18 ]
then
    echo "You are a minor"
elif [ $age -ge 18 ] && [ $age -lt 65 ]
then
    echo "You are an adult"
else
    echo "You are a senior citizen"
fi

File Testing

Bash provides operators for file testing in if statements:

  • -e: File exists
  • -f: Regular file
  • -d: Directory
  • -r: Readable
  • -w: Writable
  • -x: Executable

String Comparison

For string comparisons, use double square brackets:

#!/bin/bash

name="John"

if [[ "$name" == "John" ]]
then
    echo "Hello, John!"
else
    echo "You're not John"
fi

Best Practices

  • Always quote variables to prevent word splitting and globbing.
  • Use double square brackets [[ ]] for string comparisons and pattern matching.
  • For arithmetic comparisons, use (( )) instead of [ ].
  • Keep your conditions simple and readable.

Related Concepts

To further enhance your Bash scripting skills, explore these related topics:

By mastering if-else statements, you'll be able to create more dynamic and responsive Bash scripts, enhancing your shell scripting capabilities.