TExcelTAD
Home › Linux & Bash › Bash Exercises

Bash Exercises

Time to practise! Each exercise has a starter playground that runs as-is and prints a placeholder result, so you can see the expected format. Replace the TODO parts, press ▶ Run, and compare your output with the "Expected" lines. If you get stuck, open the solution, but give it a few minutes first: struggling a little is how the commands stick.

# Exercise Topics
1 Word statistics wc, tr, pipes
2 Biggest files find, sort, head
3 Sales by region awk, associative arrays
4 Batch rename for, globs, parameter expansion
5 Failed logins grep, cut, sort, uniq
6 Input validator functions, [[ =~ ]], case
7 Options with getopts script arguments
8 Config file loader while read, arrays, IFS

1. Word statistics

Count the lines, words and distinct words (case-insensitive) in poem.txt, and print the most frequent word.

Expected:

text
lines: 4
words: 23
distinct: 13
most frequent: the
bash · try it yourself
cat > poem.txt <<'TXT'
The wind and the rain
and the sound of the sea
sing the song of the night
to the town and the tree
TXT
# TODO: compute the four values with wc, tr, sort and uniq
echo "lines: 0"
echo "words: 0"
echo "distinct: 0"
echo "most frequent: ?"
lines: 0
words: 0
distinct: 0
most frequent: ?
Show solution
bash
echo "lines: $(wc -l < poem.txt)"
echo "words: $(wc -w < poem.txt)"
words() { tr -cs '[:alpha:]' '\n' < poem.txt | tr '[:upper:]' '[:lower:]' | grep -v '^
  

; }
echo "distinct: $(words | sort -u | wc -l)"
echo "most frequent: $(words | sort | uniq -c | sort -rn | head -n 1 | awk '{ print $2 }')"

tr -cs '[:alpha:]' '\n' puts one word per line; lower-casing first makes The and the the same word.

2. Biggest files

Print the 3 largest files under data/ with their size in bytes, largest first, formatted as SIZE PATH.

Expected:

text
9000 data/2026/march.csv
5000 data/archive/old.csv
1200 data/2026/feb.csv
bash · try it yourself
mkdir -p data/2026 data/archive
head -c 9000 /dev/zero > data/2026/march.csv
head -c 1200 /dev/zero > data/2026/feb.csv
head -c 300 /dev/zero > data/2026/jan.csv
head -c 5000 /dev/zero > data/archive/old.csv
head -c 80 /dev/zero > data/readme.txt
# TODO: find + sort + head
find data -type f | sort | head -n 3
data/2026/feb.csv
data/2026/jan.csv
data/2026/march.csv
Show solution
bash
find data -type f -printf '%s %p\n' | sort -rn | head -n 3

Without GNU find's -printf, use find data -type f -exec du -b {} + | sort -rn | head -n 3 (tab-separated).

3. Sales by region

sales.csv has a header and the columns date,region,amount. Print the total per region, sorted by region name, with two decimals, followed by the grand total.

Expected:

text
east    310.00
north   420.50
south   155.25
TOTAL   885.75
bash · try it yourself
cat > sales.csv <<'CSV'
date,region,amount
2026-03-01,north,120.50
2026-03-01,south,80.00
2026-03-02,east,310.00
2026-03-02,north,300.00
2026-03-03,south,75.25
CSV
# TODO: sum the amount per region with awk
awk -F, 'NR > 1 { print $2 }' sales.csv
north
south
east
north
south
Show solution
bash
awk -F, 'NR > 1 { sum[$2] += $3; total += $3 }
         END { for (r in sum) printf "%-6s %7.2f\n", r, sum[r] }' sales.csv | sort
awk -F, 'NR > 1 { total += $3 } END { printf "%-6s %7.2f\n", "TOTAL", total }' sales.csv

The sort must only see the per-region lines, otherwise TOTAL would be sorted between them, which is why the total is printed by a second command.

4. Batch rename

Rename every .jpeg file to .jpg and replace spaces in the names with underscores. Then list the directory.

Expected:

text
beach_day.jpg
city.jpg
notes.txt
summer_party_2026.jpg
bash · try it yourself
mkdir photos && cd photos
touch "beach day.jpeg" city.jpeg "summer party 2026.jpeg" notes.txt
# TODO: loop over *.jpeg and mv each file to its new name
for f in *.jpeg; do
  echo "would rename: $f"
done
ls
would rename: beach day.jpeg
would rename: city.jpeg
would rename: summer party 2026.jpeg
beach day.jpeg
city.jpeg
notes.txt
summer party 2026.jpeg
Show solution
bash
for f in *.jpeg; do
  new="${f%.jpeg}.jpg"
  new="${new// /_}"
  mv -- "$f" "$new"
done
ls

${f%.jpeg} strips the extension and ${new// /_} replaces all spaces. Quoting "$f" is essential because the names contain spaces.

5. Failed logins

From auth.log, list the IP addresses with failed password attempts and how many each made, most attempts first. Only include IPs with 2 or more failures.

Expected:

text
203.0.113.9 3
198.51.100.4 2
bash · try it yourself
cat > auth.log <<'LOG'
Mar 15 10:01:12 tad sshd: Failed password for root from 203.0.113.9
Mar 15 10:01:15 tad sshd: Failed password for root from 203.0.113.9
Mar 15 10:02:01 tad sshd: Accepted publickey for ada from 192.0.2.10
Mar 15 10:03:44 tad sshd: Failed password for admin from 198.51.100.4
Mar 15 10:03:50 tad sshd: Failed password for admin from 198.51.100.4
Mar 15 10:04:02 tad sshd: Failed password for guest from 192.0.2.77
Mar 15 10:05:30 tad sshd: Failed password for root from 203.0.113.9
LOG
# TODO: grep the failures, extract the IP (last field), count, filter, sort
grep -c Failed auth.log
6
Show solution
bash
grep 'Failed password' auth.log | awk '{ print $NF }' | sort | uniq -c \
  | awk '$1 >= 2 { print $2, $1 }' | sort -k2,2nr

This is the core of tools like fail2ban, which block IPs that fail too often.

6. Input validator

Write a function check VALUE that prints what kind of value it got: integer, decimal, email, date (YYYY-MM-DD) or text, and returns status 1 for empty input (printing empty).

Expected:

text
42 -> integer
-7 -> integer
3.14 -> decimal
ada@example.com -> email
2026-03-15 -> date
hello world -> text
 -> empty (status 1)
bash · try it yourself
check() {
  local v=$1
  # TODO: use [[ $v =~ ... ]] tests (or case patterns)
  echo "$v -> text"
}
for value in 42 -7 3.14 ada@example.com 2026-03-15 "hello world"; do
  check "$value"
done
check "" || echo "(status $?)"
42 -> text
-7 -> text
3.14 -> text
ada@example.com -> text
2026-03-15 -> text
hello world -> text
 -> text
Show solution
bash
check() {
  local v=$1
  if [[ -z $v ]]; then echo -n " -> empty "; return 1
  elif [[ $v =~ ^-?[0-9]+$ ]]; then echo "$v -> integer"
  elif [[ $v =~ ^-?[0-9]+\.[0-9]+$ ]]; then echo "$v -> decimal"
  elif [[ $v =~ ^[^@[:space:]]+@[^@[:space:]]+\.[a-z]+$ ]]; then echo "$v -> email"
  elif [[ $v =~ ^[0-9]{4}-[0-9]{2}-[0-9]{2}$ ]]; then echo "$v -> date"
  else echo "$v -> text"
  fi
}
for value in 42 -7 3.14 ada@example.com 2026-03-15 "hello world"; do
  check "$value"
done
check "" || echo "(status $?)"

Order matters: test the most specific patterns first. echo -n keeps the status message on the same line.

7. Options with getopts

Complete greet.sh so that it accepts -n NAME (default world), -u (upper-case the output) and -c COUNT (repeat the greeting, default 1), and treats remaining arguments as extra words appended to the greeting.

Expected:

text
Hello, world!
HELLO, ADA!
HELLO, ADA!
Hello, Linus! nice to see you
bash · try it yourself
cat > greet.sh <<'SCRIPT'
#!/usr/bin/env bash
name="world"
# TODO: parse -n NAME, -u and -c COUNT with getopts, then shift
msg="Hello, $name!"
echo "$msg"
SCRIPT
bash greet.sh
bash greet.sh -u -n Ada -c 2
bash greet.sh -n Linus nice to see you
Hello, world!
Hello, world!
Hello, world!
Show solution
bash
#!/usr/bin/env bash
name="world"; upper=0; count=1
while getopts "n:uc:" opt; do
  case $opt in
    n) name=$OPTARG ;;
    u) upper=1 ;;
    c) count=$OPTARG ;;
    *) echo "usage: greet.sh [-n NAME] [-u] [-c COUNT] [WORDS...]" >&2; exit 2 ;;
  esac
done
shift $(( OPTIND - 1 ))
msg="Hello, $name!"
(( $# > 0 )) && msg="$msg $*"
(( upper )) && msg=${msg^^}
for (( i = 0; i < count; i++ )); do echo "$msg"; done

8. Config file loader

Read app.conf into an associative array: skip blank lines and # comments, trim spaces around =, and print the keys sorted as key => value. Finally print the value of port, or 8080 if it's missing.

Expected:

text
db_host => db.internal
log_level => debug
name => TAD Shop
port => 9000
port is 9000
bash · try it yourself
cat > app.conf <<'CONF'
# shop settings
name = TAD Shop
port=9000

db_host =db.internal
# log_level = info
log_level= debug
CONF
declare -A conf
# TODO: while IFS='=' read -r key value; do ... done < app.conf
echo "port is ${conf[port]:-8080}"
port is 8080
Show solution
bash
declare -A conf
while IFS='=' read -r key value; do
  key=$(echo "$key" | xargs)          # xargs trims surrounding spaces
  [[ -z $key || $key == \#* ]] && continue
  value="${value#"${value%%[![:space:]]*}"}"   # trim leading spaces
  conf[$key]=$value
done < app.conf
for k in $(printf '%s\n' "${!conf[@]}" | sort); do
  echo "$k => ${conf[$k]}"
done
echo "port is ${conf[port]:-8080}"

IFS='=' makes read split at the first =; everything after it (even another =) goes into value. The odd-looking expansion removes leading whitespace using only Bash.

Test yourself

Which pipeline counts how often each line occurs, most frequent first?

  1. sort | uniq | sort -r
  2. sort | uniq -c | sort -rn
  3. uniq -c | sort
  4. sort -u | wc -l

Why do the rename loop's mv arguments need double quotes?

  1. mv requires quotes
  2. The file names contain spaces and would be split into several arguments
  3. To expand the glob
  4. To make mv verbose