This lesson puts the chapter together in one script. The script gets a directory as its argument, and checks that the files the shop needs are there.
bash
#!/bin/bash
# Usage: check-shop.sh DIR
if [ $# -ne 1 ]; then
echo "usage: check-shop.sh DIR"
exit 2
fi
dir="$1"
missing=0
for f in prices.txt menu.txt rota.txt; do
if [ -f "$dir/$f" ]; then
echo "ok: $f"
else
echo "missing: $f"
missing=1
fi
done
exit $missingHow it works
1. Check the arguments[ $# -ne 1 ]: wrong use ends with code 2
2. Give names to the valuesdir="$1", missing=0
3. Check each filefor f in …: one turn for each file
4. End with the right exit codeexit $missing: 0 when all are there, 1 when not
The loop does not stop at the first missing file. It writes a line for every file, and remembers in missing that something was wrong. The last line uses that variable as the exit code.
text
learner@tidepool:~$ ./check-shop.sh ~/shop
ok: prices.txt
missing: menu.txt
ok: rota.txt
learner@tidepool:~$ echo $?
1