Bash if else Statment

If-Else Statement in Bash

The if-else statement in Bash is a conditional construct used to execute a block of code based on whether a condition evaluates to true or false. It’s essential for decision-making in scripts.

Syntax

if [ condition ]; then # Commands to execute if condition is true elif [ another_condition ]; then # Commands to execute if another_condition is true else # Commands to execute if no condition is true fi

Key Points:

  • [ condition ] evaluates the condition. Use [ ] or [[ ]] for the test expressions.
  • then starts the block of commands for a true condition.
  • elif adds additional conditions (optional).
  • else handles cases where no conditions are met (optional).
  • fi ends the if-else block.

Basic Example: Simple If-Else

read -p "Enter a number: " num if [ $num -gt 10 ]; then echo "The number is greater than 10." else echo "The number is 10 or less." fi

Output (if input is 15):

The number is greater than 10.

Example: If-Elif-Else

read -p "Enter a number: " num if [ $num -lt 0 ]; then echo "The number is negative." elif [ $num -eq 0 ]; then echo "The number is zero." else echo "The number is positive." fi

Comparing Strings

You can use the if-else statement to compare strings:

read -p "Enter your favorite color: " color if [ "$color" = "blue" ]; then echo "Blue is a cool color!" elif [ "$color" = "red" ]; then echo "Red is vibrant!" else echo "That's a unique choice!" fi

File Conditions

Bash provides several operators to test files:

OperatorDescription
-eFile exists
-fThe file is a regular file
-dDirectory exists
-rFile is readable
-wFile is writable
-xFile is executable

Example: Check if a file exists

read -p "Enter a file name: " filename if [ -e "$filename" ]; then echo "The file exists." else echo "The file does not exist." fi

Logical Operators

You can combine conditions using logical operators:

OperatorDescription
&&Logical AND
`
!Logical NOT

Example: Multiple Conditions

read -p "Enter a number: " num if [ $num -gt 0 ] && [ $num -lt 100 ]; then echo "The number is between 1 and 99." else echo "The number is out of range." fi

Using [[ ]] for Advanced Tests

The [[ ]] construct allows for advanced string comparisons and pattern matching.

Example: Pattern Matching

read -p "Enter a filename: " filename if [[ $filename == *.txt ]]; then echo "This is a text file." else echo "This is not a text file." fi

Inline If-Else (Ternary-Like)

Bash supports a compact form of if-else using && and || operators:

[ $num -gt 10 ] && echo "Greater than 10" || echo "10 or less"

Error Handling with If-Else

You can handle errors in scripts using if-else:

if cp file.txt /backup/; then echo "Backup successful." else echo "Backup failed." fi

Common Errors to Avoid

  1. Spaces in Conditions: Always use spaces inside [ ] or [[ ]]:

    if [ $num -eq 10 ]; then # Correct if [$num -eq 10]; then # Incorrect
  2. Quoting Variables: Quote variables to avoid issues with spaces or special characters:

    if [ "$var" = "value" ]; then # Correct if [ $var = value ]; then # Can cause errors
  3. Misusing Logical Operators: Use && and || carefully. For example:

    [ $a -gt 5 ] && echo "True" || echo "False" # Inline check

Conclusion

The a if-else statement is a fundamental building block for decision-making in Bash scripting. With its flexibility and simplicity, you can use it to handle a wide range of scenarios, from basic checks to complex logic.

Let me know if you’d like additional examples or refinements!

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
Ad