Bird
Raised Fist0
Bash Scriptingscripting~15 mins

if-then-fi structure in Bash Scripting - Deep Dive

Choose your learning style10 modes available
Overview - if-then-fi structure
What is it?
The if-then-fi structure is a way to make decisions in bash scripts. It checks if a condition is true, and if it is, it runs some commands. The 'fi' marks the end of this decision block. This helps scripts do different things based on different situations.
Why it matters
Without the if-then-fi structure, scripts would run the same commands every time, no matter what. This would make scripts less useful because they couldn't react to changing conditions like checking if a file exists or if a number is bigger than another. It makes automation smarter and more flexible.
Where it fits
Before learning if-then-fi, you should know basic bash commands and how to run scripts. After mastering if-then-fi, you can learn else and elif for more complex decisions, and loops to repeat actions.
Mental Model
Core Idea
If a condition is true, then run some commands; otherwise, skip them until the end marked by fi.
Think of it like...
It's like a traffic light: if the light is green, then you go; if not, you wait until the light changes.
┌───────────────┐
│ if condition? │
└──────┬────────┘
       │ yes
       ▼
  ┌───────────┐
  │ run code  │
  └────┬──────┘
       │
      fi (end)
Build-Up - 7 Steps
1
FoundationBasic if-then-fi syntax
🤔
Concept: Learn the simplest form of if-then-fi to run commands when a condition is true.
Example: if [ 5 -gt 3 ] then echo "5 is greater than 3" fi This checks if 5 is greater than 3. If yes, it prints the message.
Result
5 is greater than 3
Understanding the basic syntax is the first step to controlling script flow based on conditions.
2
FoundationUsing test conditions inside if
🤔
Concept: Learn how to write conditions inside the if statement using test commands like [ ] or [[ ]].
Example: if [ -f myfile.txt ] then echo "File exists" fi This checks if 'myfile.txt' exists as a file.
Result
File exists (if the file is present)
Knowing how to test conditions lets you check real-world things like files or numbers before deciding what to do.
3
IntermediateAdding else for alternative actions
🤔Before reading on: do you think else runs when the if condition is true or false? Commit to your answer.
Concept: Learn how to add an else block to run commands when the if condition is false.
Example: if [ -d myfolder ] then echo "Folder exists" else echo "Folder does not exist" fi This prints one message if the folder exists, another if it doesn't.
Result
Folder exists (if folder is there) or Folder does not exist (if not)
Adding else lets scripts handle both yes and no cases, making decisions complete.
4
IntermediateUsing elif for multiple conditions
🤔Before reading on: do you think elif can replace multiple nested if-else statements? Commit to your answer.
Concept: Learn how to check several conditions in order using elif blocks.
Example: if [ $num -gt 10 ] then echo "Greater than 10" elif [ $num -eq 10 ] then echo "Equal to 10" else echo "Less than 10" fi This checks if a number is greater, equal, or less than 10.
Result
One of the three messages depending on $num
Elif simplifies checking many conditions without deep nesting, improving readability.
5
AdvancedCombining conditions with logical operators
🤔Before reading on: do you think you can check two conditions at once inside a single if? Commit to your answer.
Concept: Learn to use && (and) and || (or) to combine multiple conditions in one if statement.
Example: if [ -f file1 ] && [ -f file2 ] then echo "Both files exist" fi This runs the command only if both files exist.
Result
Both files exist (if both are present)
Combining conditions lets scripts make smarter decisions based on multiple facts at once.
6
AdvancedUsing if-then-fi in scripts with variables
🤔Before reading on: do you think variables inside conditions need special syntax? Commit to your answer.
Concept: Learn how to use variables inside if conditions and how to compare their values.
Example: name="Alice" if [ "$name" = "Alice" ] then echo "Hello, Alice!" fi This checks if the variable name equals 'Alice'.
Result
Hello, Alice!
Using variables in conditions makes scripts dynamic and able to react to changing data.
7
ExpertPitfalls with spaces and quoting in conditions
🤔Before reading on: do you think missing spaces inside [ ] or missing quotes can cause errors? Commit to your answer.
Concept: Understand common syntax errors like missing spaces around brackets and why quoting variables is important.
Wrong: if [$name="Alice"] then echo "Hi" fi Right: if [ "$name" = "Alice" ] then echo "Hi" fi Missing spaces or quotes cause syntax errors or wrong behavior.
Result
Right version prints 'Hi'; wrong version causes error or unexpected results.
Knowing these syntax rules prevents frustrating bugs that are hard to spot.
Under the Hood
The shell reads the if statement and evaluates the condition inside [ ] or [[ ]]. It runs the test command to check the condition. If the test returns true (exit code 0), the shell executes the commands after then until it reaches fi. If false (non-zero exit code), it skips to else or fi. The shell uses exit codes to decide flow.
Why designed this way?
This design follows Unix philosophy of using simple commands and exit codes for decisions. It keeps syntax minimal and consistent with other shell commands. The fi keyword was chosen as 'if' spelled backwards to mark the end clearly. Alternatives like braces or keywords were possible but this style is concise and readable.
┌───────────────┐
│  Evaluate     │
│  condition    │
└──────┬────────┘
       │ (exit code 0 = true)
       ▼
  ┌───────────┐   no
  │ then block│─────────┐
  └────┬──────┘         │
       │                ▼
       ▼               else block (optional)
  ┌───────────┐         │
  │ execute   │         │
  │ commands  │         │
  └────┬──────┘         │
       │                │
       ▼                │
      fi <──────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does if [ condition ] run commands when the condition is false? Commit yes or no.
Common Belief:If the condition inside if is false, the commands inside then still run.
Tap to reveal reality
Reality:Commands inside then run only if the condition is true; if false, they are skipped.
Why it matters:Believing this causes scripts to behave incorrectly, running commands when they shouldn't.
Quick: Can you omit spaces inside [ ] in if statements? Commit yes or no.
Common Belief:You can write if [condition] without spaces and it works fine.
Tap to reveal reality
Reality:Spaces around brackets and between tokens are required; missing them causes syntax errors.
Why it matters:Missing spaces leads to confusing errors that beginners struggle to fix.
Quick: Does quoting variables inside [ ] always cause errors? Commit yes or no.
Common Belief:Quoting variables inside conditions is optional and doesn't affect results.
Tap to reveal reality
Reality:Quoting variables prevents errors when variables are empty or contain spaces; not quoting can break scripts.
Why it matters:Not quoting variables causes scripts to fail unexpectedly with empty or special values.
Quick: Does fi mean 'finish' or something else? Commit your guess.
Common Belief:fi is just a random keyword with no special meaning.
Tap to reveal reality
Reality:fi is 'if' spelled backwards, marking the end of the if block clearly.
Why it matters:Knowing this helps remember syntax and avoid confusion with other keywords.
Expert Zone
1
The shell uses exit codes (0 for true, non-zero for false) from test commands to decide flow, not boolean true/false values.
2
Using [[ ]] instead of [ ] allows more powerful tests and safer syntax, like pattern matching and no word splitting.
3
Stacking multiple if-then-fi blocks can be optimized by using case statements or functions for cleaner code.
When NOT to use
If you need to handle many complex conditions, using case statements or external scripting languages like Python may be clearer and more maintainable.
Production Patterns
In real scripts, if-then-fi is used to check file existence, user input, command success, and environment variables before proceeding. It is often combined with functions and error handling for robust automation.
Connections
Boolean Logic
if-then-fi uses boolean logic to decide which commands to run based on true/false conditions.
Understanding boolean logic helps write correct conditions and combine them with && and || operators.
Flow Control in Programming
if-then-fi is a basic flow control structure similar to if statements in other programming languages.
Knowing this connection helps transfer scripting skills to languages like Python, JavaScript, or C.
Decision Making in Everyday Life
if-then-fi mirrors how people make choices: if a condition is met, then take an action.
Recognizing this pattern in daily decisions makes scripting logic more intuitive and relatable.
Common Pitfalls
#1Missing spaces around brackets causing syntax errors.
Wrong approach:if [ $name="Alice" ] then echo "Hi" fi
Correct approach:if [ "$name" = "Alice" ] then echo "Hi" fi
Root cause:Beginners often forget that [ ] is a command requiring spaces around it and that = needs spaces around it too.
#2Not quoting variables leading to errors when variables are empty or contain spaces.
Wrong approach:if [ $file = "myfile" ] then echo "Found" fi
Correct approach:if [ "$file" = "myfile" ] then echo "Found" fi
Root cause:Variables without quotes can split into multiple words or become empty, breaking the test command.
#3Using single brackets [ ] with complex expressions that require [[ ]] syntax.
Wrong approach:if [ $num -gt 5 && $num -lt 10 ] then echo "Between 5 and 10" fi
Correct approach:if [[ $num -gt 5 && $num -lt 10 ]] then echo "Between 5 and 10" fi
Root cause:Single brackets do not support && inside; double brackets are needed for complex logical operators.
Key Takeaways
The if-then-fi structure lets bash scripts make decisions by running commands only when conditions are true.
Conditions inside if use test commands with spaces and quoting to avoid syntax errors and unexpected behavior.
Adding else and elif blocks allows handling multiple outcomes clearly and cleanly.
Logical operators && and || combine conditions for smarter decision-making in one if statement.
Understanding shell exit codes and syntax rules prevents common bugs and makes scripts reliable.

Practice

(1/5)
1. What is the purpose of the if-then-fi structure in a bash script?
easy
A. To run commands only if a certain condition is true
B. To repeat commands multiple times
C. To define a function
D. To declare a variable

Solution

  1. Step 1: Understand the role of if-then-fi

    The if-then-fi structure checks a condition and runs commands only if that condition is true.
  2. Step 2: Compare with other options

    Repeating commands is done with loops, functions define reusable code, and variables store data, so these do not match if-then-fi.
  3. Final Answer:

    To run commands only if a certain condition is true -> Option A
  4. Quick Check:

    if-then-fi controls conditional execution = D [OK]
Hint: If you want to do something only when true, use if-then-fi [OK]
Common Mistakes:
  • Confusing if-then-fi with loops
  • Thinking if-then-fi defines functions
  • Using if-then-fi to declare variables
2. Which of the following is the correct syntax for a simple if statement in bash?
easy
A. if $x > 5 then echo "Yes" fi
B. if ($x > 5) { echo "Yes" }
C. if [ $x -gt 5 ]; then echo "Yes"; fi
D. if $x -gt 5 echo "Yes" fi

Solution

  1. Step 1: Check the correct if syntax in bash

    Bash requires conditions inside square brackets with spaces, then 'then', commands, and ending with 'fi'. if [ $x -gt 5 ]; then echo "Yes"; fi matches this.
  2. Step 2: Identify errors in other options

    if ($x > 5) { echo "Yes" } uses wrong syntax with parentheses and braces (not bash). if $x > 5 then echo "Yes" fi misses semicolons and brackets. if $x -gt 5 echo "Yes" fi misses 'then' keyword.
  3. Final Answer:

    if [ $x -gt 5 ]; then echo "Yes"; fi -> Option C
  4. Quick Check:

    Correct bash if syntax = C [OK]
Hint: Remember: if [ condition ]; then ... fi with spaces [OK]
Common Mistakes:
  • Missing spaces inside [ ]
  • Omitting 'then' keyword
  • Using wrong brackets or symbols
3. What will be the output of this script?
#!/bin/bash
x=10
if [ $x -lt 5 ]; then
echo "Less"
fi
echo "Done"
medium
A. No output
B. Less Done
C. Less
D. Done

Solution

  1. Step 1: Evaluate the condition

    The variable x is 10. The condition checks if 10 is less than 5, which is false.
  2. Step 2: Determine which commands run

    Since the condition is false, the echo "Less" inside if does not run. The echo "Done" after if runs always.
  3. Final Answer:

    Done -> Option D
  4. Quick Check:

    Condition false, only "Done" prints = A [OK]
Hint: If condition false, skip if block, run commands after fi [OK]
Common Mistakes:
  • Assuming if block runs even if condition false
  • Confusing -lt with -gt
  • Ignoring commands after fi
4. Identify the error in this bash script snippet:
if [ $num -eq 5 ]
then
  echo "Number is five"
fi
medium
A. Missing semicolon or newline after condition
B. No error, script is correct
C. Missing fi keyword
D. Wrong comparison operator

Solution

  1. Step 1: Check if syntax correctness

    The condition is inside [ ] with spaces, '-eq' is correct for numeric equality, 'then' is on next line, and 'fi' closes the block.
  2. Step 2: Confirm no syntax errors

    Newline after condition is valid instead of semicolon. All keywords are present and correctly placed.
  3. Final Answer:

    No error, script is correct -> Option B
  4. Quick Check:

    Proper if-then-fi syntax = B [OK]
Hint: Newline after condition is allowed instead of semicolon [OK]
Common Mistakes:
  • Thinking newline after condition is error
  • Confusing -eq with other operators
  • Forgetting fi keyword
5. You want to write a script that prints "Even" if a number stored in n is even, and "Odd" otherwise. Which of these is the correct if-then-fi structure to do this?
hard
A. if [ $((n % 2)) -eq 0 ]; then echo "Even"; else echo "Odd"; fi
B. if [ $n % 2 == 0 ]; then echo "Even"; else echo "Odd"; fi
C. if (( n % 2 == 0 )) then echo "Even"; else echo "Odd"; fi
D. if [ $n / 2 -eq 0 ]; then echo "Even"; else echo "Odd"; fi

Solution

  1. Step 1: Understand how to check evenness in bash

    We use arithmetic expansion $(( )) to calculate remainder of n divided by 2. If remainder is 0, number is even.
  2. Step 2: Analyze each option's correctness

    if [ $((n % 2)) -eq 0 ]; then echo "Even"; else echo "Odd"; fi correctly uses [ $((n % 2)) -eq 0 ] with then, else, fi. if [ $n % 2 == 0 ]; then echo "Even"; else echo "Odd"; fi uses invalid syntax inside [ ]. if (( n % 2 == 0 )) then echo "Even"; else echo "Odd"; fi misses semicolon before 'then' causing syntax error. if [ $n / 2 -eq 0 ]; then echo "Even"; else echo "Odd"; fi incorrectly uses division instead of modulo.
  3. Final Answer:

    if [ $((n % 2)) -eq 0 ]; then echo "Even"; else echo "Odd"; fi -> Option A
  4. Quick Check:

    Modulo with $(( )) inside [ ] and proper if-then-fi = A [OK]
Hint: Use $(( )) for math inside [ ] in if-then-fi [OK]
Common Mistakes:
  • Using % inside [ ] without $(( ))
  • Using == instead of -eq for numbers
  • Confusing division with modulo
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard