0
0
Bash Scriptingscripting~15 mins

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

Choose your learning style9 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.