Linux for Developers Course
Linux for Developers
/
Intermediate

If/Else Statements

Definition

Conditional logic structures in Bash that allow a script to execute different commands based on whether a specific test evaluates to True or False.

Explain Like I'm New

Decision making for scripts. 'IF the database is turned off, THEN start it up. ELSE, do nothing.'

Real World Example

A script checks if a critical file exists before trying to read it: `if [ -f "config.json" ]; then` ` cat config.json` `else` ` echo "Error: File missing!"` `fi`

Common Use Cases

  • •Error handling
  • •System checks before execution

Interview Questions

basic

  • What mandatory word must you use to close (end) an `if` statement block in Bash?

intermediate

  • What does the test condition `[ -d "/var/log" ]` evaluate?

Flash Cards

Question

Close the if block?

Click to reveal answer
Answer

`fi` (which is literally the word 'if' spelled backward).

Question

What does -d do?

Click to reveal answer
Answer

It is a Directory check. The condition evaluates to True ONLY if the path `/var/log` actually exists on the hard drive AND is a directory (not a file).