Back to Blog
Arnošt Havelka

Premium: Bash Script Practice

Combine variables, functions, loops, and conditionals to solve a realistic multi-step scenario.

Start Interactive Lesson
Premium: Bash Script Practice

Premium: Bash Script Practice

Now combine everything: variables, functions, loops, and conditionals to build a real-world automation script.

Step 1: Build the Foundation

Command Prompt
(empty)
C:\Users\User>ls

Create multiple log files with a loop. Each iteration writes a new file.

Step 2: Analyze the Results

Command Prompt
log_1.txt log_2.txt log_3.txt
C:\Users\User>ls backups

Use glob patterns to process all files at once.

Step 3: Extract and Count

Command Prompt
Log entry 1 Log entry 2 Log entry 3
C:\Users\User>cat backups/*.txt

Combine pipes and commands to get meaningful statistics from your data.

Real-World Scenario

You're managing 10 microservices. Each generates a deploy log. Build a script that:

  1. Creates a backup directory with all current logs.
  2. Filters for error lines.
  3. Counts total errors across all services.
function check_deploys {
  mkdir -p backup_deploys
  for service in web api cache queue worker db; do
    if [ -f "$service.log" ]; then
      cp "$service.log" backup_deploys/
      error_count=$(grep -c 'ERROR' "backup_deploys/$service.log")
      echo "Service $service has $error_count errors"
    fi
  done
}

check_deploys

Checklist You Can Reuse

  1. Iterate with for var in list; do ...; done.
  2. Check conditions with if [ test ]; then ...; fi.
  3. Capture output with $(command).
  4. Process files with cat *.ext | grep | wc -l.
  5. Organize with functions that bundle related tasks.

Knowledge Check

1 / 2

How do you run a command and store its result in a variable?

References

These Microsoft Learn and Windows documentation links provide authoritative details for the commands used in this article.

Up Next

PS - List Processes

View running processes in Bash.