Mastering Bash: Variables, Loops, and Conditionals for Everyday Automation
Introduction
Tired of typing the same commands over and over? In this post we’ll expand on the short video that showed how to build a simple Bash script using variables, loops, and conditionals. By the end you’ll understand the core Bash constructs and be ready to automate your daily Linux tasks.
Why Script?
Repeating commands manually wastes time and introduces human error. A script captures the logic once, makes it portable, and can be version‑controlled.
Core Concepts
Variables
In Bash a variable is defined without spaces:
greeting="Hello"
You reference it with a leading $:
echo "$greeting, world"
Quotes preserve whitespace and prevent word splitting.
Loops
The for loop can iterate over a range:
for i in {1..5}; do
echo "Iteration $i"
done
The {1..N} brace expansion generates the sequence automatically.
Conditionals
Bash offers several test syntaxes. For arithmetic you can use (( )):
count=3
if (( count > 2 )); then
echo "Count is high"
else
echo "Count is low"
fi
A compact ternary‑style expression can be written with && and ||:
(( i % 2 )) && echo "odd $i" || echo "even $i"
Full Example: Greeting with Odd/Even Logic
Create a file called automate.sh:
#!/bin/bash
greeting="Hello"
for i in {1..3}; do
(( i % 2 )) && echo "$greeting, odd $i" || echo "$greeting, even $i"
done
Make it executable and run it:
chmod +x automate.sh
./automate.sh
Output:
Hello, odd 1
Hello, even 2
Hello, odd 3
Best Practices
-
Shebang: Always start scripts with
#!/usr/bin/env bashor#!/bin/bashto guarantee the interpreter. -
Quote Variables: Use double quotes around variables (
"$var") to avoid word splitting and globbing. -
Set
-eand-u: Addset -euo pipefailat the top of scripts to exit on errors, treat unset variables as errors, and catch pipeline failures. -
Use Functions: Break complex logic into reusable functions.
-
Avoid
eval: It can lead to security vulnerabilities. -
Prefer
$(...)over backticks: For command substitution,$(command)is more readable and nestable.
Common Pitfalls
| Pitfall | Symptom | Fix |
|---|---|---|
Missing spaces around = |
greeting = "Hi" produces an error |
Write greeting="Hi" |
| Unquoted variables in loops | Word splitting on spaces | Use "$var" |
Using [ for arithmetic |
[ cannot evaluate i%2 |
Use (( )) |
| Not marking script executable | Permission denied |
Run chmod +x script.sh |
Extending the Script
You can turn the example into a generic utility:
#!/usr/bin/env bash
set -euo pipefail
greeting="${1:-Hello}"
max="${2:-5}"
for i in $(seq 1 "$max"); do
if (( i % 2 )); then
echo "$greeting, odd $i"
else
echo "$greeting, even $i"
fi
done
Now you can call it with custom greeting and count:
./automate.sh "Hi there" 7
Conclusion
Encapsulating repetitive logic in Bash scripts saves time, reduces errors, and makes your workflow reproducible. Start small, apply the best practices above, and gradually build more sophisticated automation pipelines.
Related Posts
Linux Commands Every Developer Should Know
A practical guide to the terminal commands that show up in daily development, debugging, and server work.
Useful Linux Commands for Logs and File Search
A production-style walkthrough of find, tail, journalctl, grep, and awk for server troubleshooting.
Demystifying Kubernetes Service Discovery
Unlock the full potential of Kubernetes with our comprehensive guide to service discovery, enabling seamless communication between services within your cluster.
Harnessing the Power of Kubernetes: Pods and Deployments Demystified
Discover how Kubernetes Pods and Deployments provide powerful tools for managing and scaling applications efficiently within containerized environments.