OSBash.004: Conditional Tests — if, then, else, fi, and [[ ]]

Anime illustration of a Linux learner studying Bash conditional expressions at a desk.

This lesson introduces conditional tests in Bash: how a shell script chooses what to do when a condition is true or false. It follows OSBash.003 on variables and expansion.

Learning Objectives

Recognize if, then, else and fi; test whether a directory exists; compare strings safely; understand the meaning of an exit status.

The Basic if Statement

A Bash if statement runs a command and checks its exit status. Status zero means success; a nonzero status means failure. The shell executes the then branch only when the tested command succeeds.

if true; then echo "Condition passed"; else echo "Condition failed"; fi

Check Whether a Directory Exists

The [[ ... ]] test expression is built into Bash. The -d operator checks whether a path exists and is a directory.

if [[ -d /var/log ]]; then echo "Log directory found"; else echo "Log directory missing"; fi

Compare Two Strings

Use == inside [[ ... ]] for string equality. Quote variables to make intent clear, especially when teaching beginners.

role="admin"; if [[ "$role" == "admin" ]]; then echo "Administrator"; else echo "Standard user"; fi

Common Mistakes

Every if must end with fi. Use spaces around operators inside [[ ... ]]. Remember that [[ ... ]] is Bash syntax and is not guaranteed to work in every POSIX sh shell. Never assume a successful test grants authorization; it only checks the condition you wrote.

Knowledge Check

1. What exit status means success? 2. What does -d test? 3. Which keyword ends a Bash if statement? 4. What is the purpose of else?

Answers

1. Zero. 2. Whether the path is a directory. 3. fi. 4. It supplies commands to run when the tested condition fails.

Further Reading

GNU Bash Manual — Conditional Constructs; GNU Bash Manual — Conditional Expressions.

BitcoinVersus.Tech Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True. If you would like to support to help further secure the integrity of our research initiatives, please donate using the QR code provided

For best QR-code scanning results, please scan this donation code from a desktop or larger screen. Mobile screens may prevent camera recognition.

Leave a Reply