Bash exercises with solutions
1. Count Files Beginner
Print how many entries (files and folders, excluding hidden ones) are in the current folder – with ls and wc, just the number.
Note
Connect ls with wc -l via a pipe. On macOS, wc -l produces spaces before the number – that is normal.
Show sample solution
ls | wc -l2. Greeting with a Variable Beginner
Store your name in a variable and print "Hello <name>, today is <date in YYYY-MM-DD format>!".
Note
date +%F returns the date; capture it with $(...) inside the string within double quotes.
Show sample solution
#!/usr/bin/env bash
name="Ada"
echo "Hello $name, today is $(date +%F)!"3. Even Numbers Beginner
Print all even numbers from 1 to 10, one per line.
Note
Check with (( i % 2 == 0 )) and then print $i. Alternative: seq 2 2 10.
Show sample solution
#!/usr/bin/env bash
for i in {1..10}; do
if (( i % 2 == 0 )); then
echo "$i"
fi
done4. Check a File Beginner
Write a script that expects a file name as its first argument. If the file exists, print "present (N lines)", otherwise "missing" to stderr and exit code 1. Without an argument: a usage hint, exit code 2.
Note
$# counts arguments, [[ -f "$1" ]] checks the file, wc -l < "$1" counts lines (remove spaces with tr -d ' ').
Show sample solution
#!/usr/bin/env bash
if [[ $# -lt 1 ]]; then
echo "Usage: $0 <file>" >&2
exit 2
fi
if [[ -f "$1" ]]; then
zeilen=$(wc -l < "$1" | tr -d ' ')
echo "present ($zeilen lines)"
else
echo "missing" >&2
exit 1
fi5. Errors from the Log Intermediate
From server.log (see the lesson "grep, sed, awk & Co.") print only the time (column 2) and the message of all ERROR lines, in the format "10:00:05 Database unreachable". Use awk.
Note
Filter $3 == "ERROR". Store $2 in a variable, then clear $1, $2 and $3 (set them to empty) and strip leading spaces with sub(/^ +/, "").
Show sample solution
awk '$3 == "ERROR" { zeit = $2; $1 = $2 = $3 = ""; sub(/^ +/, ""); print zeit, $0 }' server.log6. Count Cities Intermediate
In daten.csv (header line: name,stadt,alter) count how often each city occurs, sorted descending. Expected: "2 Berlin" before "1 Hamburg".
Note
Skip the header line with tail -n +2, take column 2 with cut -d, -f2, then sort | uniq -c | sort -rn.
Show sample solution
tail -n +2 daten.csv | cut -d, -f2 | sort | uniq -c | sort -rn7. Robust Backup Script Advanced
Write a script with strict mode that packs a folder (argument 1) as name-YYYYMMDD.tar.gz into a target directory (argument 2, default ./backups), creates the target if needed, ends errors with a message on stderr and exit code 1, and prints a success message with the archive name.
Note
Use ${1:?Usage ...} for required arguments, mkdir -p, tar -czf ... -C "$(dirname ...)" "$(basename ...)" and check beforehand with [[ -d ... ]].
Show sample solution
#!/usr/bin/env bash
set -euo pipefail
quelle="${1:?Usage: $0 <folder> [target]}"
ziel="${2:-./backups}"
[[ -d "$quelle" ]] || { echo "Source not found: $quelle" >&2; exit 1; }
mkdir -p "$ziel"
archiv="$ziel/$(basename "$quelle")-$(date +%Y%m%d).tar.gz"
tar -czf "$archiv" -C "$(dirname "$quelle")" "$(basename "$quelle")"
echo "Backup created: $archiv"8. Retry Function with Cleanup Advanced
Write a function retry N command... that runs a command up to N times and waits 1 second after each failure. If it gives up after N attempts, it returns exit code 1. Also create a temp directory that is guaranteed to be deleted with trap.
Note
local n=$1; shift, then for ((i = 1; i <= n; i++)); do "$@" && return 0; sleep 1; done; return 1. Note: under set -e, "$@" && return 0 is allowed because a failure before && does not trigger an abort.
Show sample solution
#!/usr/bin/env bash
set -euo pipefail
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
retry() {
local n=$1; shift
local i
for ((i = 1; i <= n; i++)); do
"$@" && return 0
echo "Attempt $i/$n failed" >&2
sleep 1
done
return 1
}
retry 3 test -f "$tmp/gibt-es-nicht" || echo "gave up"
echo "Temp: $tmp"