Skip to main content
Albero Academy

Variables, Conditionals & Loops

The programming side of Bash — variables, command substitution, if-statements and loops to automate repetitive work.

Chapter 3Bash15 min readBeginner friendly
  • #Bash
  • #Scripting
  • #Loops

Bash isn't just commands — it's a full (if quirky) programming language. Variables, conditionals and loops turn a sequence of commands into automation. The syntax is unusual, so watch the spacing carefully; it's the #1 source of beginner errors.

Variables

Assign with name=value — no spaces around the =. Read the value with a $ prefix, and quote it to be safe:

variables
name="Aanya" # no spaces around =
greeting="Hello, $name"
echo "$greeting" # Hello, Aanya — always quote variables
count=5
echo "You have $count messages"

Command substitution

Capture a command's output into a variable with $(…):

capture output
today=$(date +%Y-%m-%d)
files=$(ls | wc -l)
echo "On $today there are $files files"

Conditionals

if tests a condition inside [ … ]. Note the specific operators — Bash uses words for numbers and symbols for files:

if statements
if [ "$count" -gt 3 ]; then
echo "More than three"
elif [ "$count" -eq 0 ]; then
echo "None"
else
echo "A few"
fi
# File tests
if [ -f "config.txt" ]; then echo "file exists"; fi
if [ -d "logs" ]; then echo "directory exists"; fi
TestTrue when
-eq -ne -gt -ltNumeric equal / not / greater / less
= !=String equal / not equal
-f fileFile exists
-d dirDirectory exists
-z strString is empty

Loops

for & while
# Loop over files
for file in *.txt; do
echo "Processing $file"
done
# Loop over a list
for env in dev staging prod; do
echo "Deploying to $env"
done
# While loop
count=1
while [ "$count" -le 3 ]; do
echo "Attempt $count"
count=$((count + 1)) # arithmetic
done

Practice

Write commands (not yet a script) that: store today's date in a variable, loop over every .txt file in a folder and print its name, and use an if to print "backup exists" only when a backup/ directory is present.

Key takeaways

  1. 01Assign variables with name=value (no spaces); read with $name and always quote "$var".
  2. 02Capture command output with $(command).
  3. 03if uses [ … ] with word operators for numbers (-gt, -eq) and -f/-d for files.
  4. 04for loops iterate files or lists; while loops run until a condition is false.
  5. 05Spacing and quoting are the top sources of Bash bugs — be precise.