SkillSprout
Chapter 2 · Lesson 3
Intermediate
1 min read

Conditions and Loops

Overview

Conditions let a script choose a path. Loops repeat a block while an input set or exit condition remains valid. Begin with simple checks and add set -e only after understanding which failures should stop the script.

Detailed Notes

Test files and values

bash
#!/usr/bin/env bash

if [[ -f "$1" ]]; then
  echo "Regular file: $1"
elif [[ -d "$1" ]]; then
  echo "Directory: $1"
else
  echo "Missing: $1" >&2
  exit 1
fi
  • -f tests for a regular file.
  • -d tests for a directory.
  • >&2 sends output to stderr.
  • exit 1 ends the script with a non-zero status.

Use [[ ... ]] in Bash for file tests and variable comparisons.

for loop

bash
for name in api worker database; do
  echo "Checking $name"
done

The loop executes once for each value.

Iterate files:

bash
for file in *.conf; do
  [[ -f "$file" ]] || continue
  echo "Found $file"
done

The || continue form skips a missing literal if no file matches the pattern.

while loop

bash
count=1
while [[ $count -le 5 ]]; do
  echo "$count"
  ((count++))
done

((count++)) increments an arithmetic variable. [[ $count -le 5 ]] tests whether count is less than or equal to 5.

Practice

Write a script that accepts a directory, prints an error if it is missing and counts the regular files inside it.

Common Interview Questions

Finished this lesson?

0 of 25 lessons done · 0% of the course