Typorithm · medium

test & Conditionals

bash-conditionalsbashiftestelif
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn test & Conditionals

0%

Basics

if [ test ]; then ... fi runs a block when a test passes. [ -f file ] checks for a regular file, [ -d dir ] a directory, [ -z str ] an empty string. elif chains more conditions and else is the fallback; [[ ... ]] is bash's extended test.

An if statement runs a block based on a test. [ ... ] is the classic test command: -f "config.txt" is true when the file exists as a regular file, -d "src" when it is a directory, and -z is true for an empty string.

The ; then starts the block and fi (if spelled backwards) closes it. elif chains an additional condition tested only when earlier ones failed, and else is the catch-all that runs when nothing matched.

Bash also offers [[ ... ]], an extended test that supports && and || directly and pattern matching like [[ $x == a* ]], avoiding many quoting pitfalls of the older [ ... ] form.

01

[ ... ] is the test command; ; then and fi delimit the block.

02

-f tests a file, -d a directory, -z an empty string.

03

elif chains conditions; else is the fallback.

if [ -f "config.txt" ]; then
  echo "found"
elif [ -d "src" ]; then
  echo "dir"
else
  echo "missing"
fi

Read the implementation

Connect each part of the code to the concept before you type.

1. Test a file

[ ... ] is the test command; -f is true when config.txt is a regular file.

if [ -f "config.txt" ]; then

2. Block start

; then begins the block that runs when the condition is true.

; then

3. Else-if branch

elif chains another condition; -d is true when src is a directory.

elif [ -d "src" ]; then

4. Fallback branch

else runs when no preceding condition matched.

else

5. Block end

fi closes the if/elif/else block — if spelled backwards.

fi

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

test & Conditionals: Lesson & Practice · Typorithm | ApplyDjinn