•Arnošt Havelka
Premium: Bash Script Practice
Combine variables, functions, loops, and conditionals to solve a realistic multi-step scenario.
Start Interactive LessonNow combine everything: variables, functions, loops, and conditionals to build a real-world automation script.
Step 1: Build the Foundation
Terminal
~$mkdir -p backups
for i in 1 2 3; do echo "Log entry $i" > backups/log_$i.txt; done
ls backups
Create multiple log files with a loop. Each iteration writes a new file.
Step 2: Analyze the Results
Terminal
~$cat backups/*.txt
Use glob patterns to process all files at once.
Step 3: Extract and Count
Terminal
~$cat backups/*.txt | grep -c 'Log entry'
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:
- Creates a backup directory with all current logs.
- Filters for error lines.
- Counts total errors across all services.
printf '%s\n' 'INFO deploy started' 'ERROR health check failed' > web.log
printf '%s\n' 'INFO deploy complete' > api.log
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
- Iterate with
for var in list; do ...; done. - Check conditions with
if [ test ]; then ...; fi. - Capture output with
$(command). - Process files with
cat *.ext | grep | wc -l. - Organize with functions that bundle related tasks.
Knowledge Check
1 / 2How do you run a command and store its result in a variable?
References
These documentation links provide authoritative details for the commands used in this article.
Up Next
Premium: Bash Log Hunt
Hunt deployment failures fast with grep pipelines, counts, and saved incident notes.