task 7.2 · chapter 7 of 8: a little bash scripting · 25 min
Audit the configs
objective
Write scripts/audit.sh from scratch: list the configs in a folder that have no ntp server line, exit 1 if there are any, and handle the cases that break most first scripts: names with spaces, an empty folder, and no folder at all.
scripts/audit.shopen a file in VS Code: Ctrl+P (Cmd+P on a Mac), type its name, Enter
| Lesson | A little Bash scripting |
|---|---|
| Practice folder | files/configs: four leaf switch configs (one name has a space) and a README |
| Your script | scripts/audit.sh: the rules are in its header |
new to this? step by stepbeginner
- Read the header of scripts/audit.sh: it’s the spec.
- Check
$1is a folder ([ -d "$1" ]); if not,echoa usage line>&2andexit 2. for f in "$1"/*.cfg; do ... done; skip it if[ -e "$f" ]fails;grep -q '^ntp server' "$f"or printbasename "$f".chmod +x, try it on files/configs, thenmake check T=7.2.
more in meet the lab
Loops over files, and the tests that guard them
for loops over a glob
for f in files/configs/*.cfg; do
echo "checking $f"
done
The glob expands to every matching file, and the loop runs once for each, with f set to its path. Unlike
$(ls ...), a glob keeps a name with a space as one name, as long as you write "$f" with quotes inside the loop.
When nothing matches, though, bash leaves the pattern as it is: in an empty folder, f is the text
files/configs/*.cfg, a file that doesn’t exist. That’s why loops like this start with a check.
Tests
[ ... ] is a command whose exit code answers a question, so it goes straight into an if:
| Test | True when |
|---|---|
[ -e "$f" ] | f exists |
[ -d "$f" ] | f is a folder |
[ -z "$x" ] | x is empty |
! command | turns a command’s success into failure, and back |
grep -q: an answer, not output
grep -q PATTERN file prints nothing at all; it exits 0 if it found a match and 1 if it didn’t. ^ in the
pattern means at the start of a line, so '^ntp server' won’t match a comment that mentions ntp.
Errors go to stderr
echo "usage: ..." >&2 writes to stderr, stream 2, instead of stdout. A script that’s used in a pipeline keeps
its real output on stdout and its complaints on stderr, so the two never mix.
in one sentence Loop over a glob with “$f” quoted, guard the empty case, test with [ ] and grep -q, complain on stderr.
The practice folder
$ ls files/configs
README.txt 'chi leaf2.cfg' chi-leaf1.cfg nyc-leaf1.cfg nyc-leaf2.cfg
$ grep -c '^ntp server' files/configs/*.cfg
files/configs/chi leaf2.cfg:0
files/configs/chi-leaf1.cfg:1
files/configs/nyc-leaf1.cfg:1
files/configs/nyc-leaf2.cfg:0
ls quotes 'chi leaf2.cfg' to show it’s one name. The two with 0 are the ones your script should list.
Here’s what goes wrong without quotes:
$ for f in $(ls files/configs); do echo "[$f]"; done
[README.txt]
[chi]
[leaf2.cfg]
[chi-leaf1.cfg]
...
One file has become two names, neither of which exists.
The guard and the loop
Run the starter, and look at what it says:
run in the terminalchmod +x scripts/audit.sh ./scripts/audit.sh files/configs; echo $?Try the loop on its own in the terminal before you put it in the script:
run in the terminalfor f in files/configs/*.cfg; do echo "[$f]"; doneFour names, the spaced one in one piece.
And the test that the empty-folder case needs:
run in the terminalmkdir -p /tmp/empty for f in /tmp/empty/*.cfg; do echo "[$f]"; [ -e "$f" ] || echo " that one doesn't exist"; done
in one sentence An unmatched glob stays as text, so check [ -e "$f" ] before using it.
Write audit.sh
Replace the TODO in scripts/audit.sh with a script that does what its header says:
./scripts/audit.sh DIRprints the name (just the name, not the path) of every.cfgin DIR with no line startingntp server, one per line;- it exits 1 if it printed any, 0 if not, and an empty folder is fine;
- with no DIR, or a DIR that isn’t a folder, it prints a usage line on stderr and exits 2.
$ ./scripts/audit.sh files/configs; echo "exit $?"
chi leaf2.cfg
nyc-leaf2.cfg
exit 1
Then make check T=7.2. It runs your script on folders it hasn’t seen.
hint
Do the guard first, at the top: if [ -z "$1" ] || [ ! -d "$1" ]; then ... fi. Run it with no argument to
check it, then move on.
hint
Keep a missing=0 before the loop, like down=0 in reach.sh, and exit "$missing" at the end.
hint
basename "$f" prints a path’s last part: files/configs/chi leaf2.cfg becomes chi leaf2.cfg.
show the solution
dir="${1:-}"
if [ -z "$dir" ] || [ ! -d "$dir" ]; then
echo "usage: $0 DIR (DIR is a folder of .cfg files)" >&2
exit 2
fi
missing=0
for f in "$dir"/*.cfg; do
[ -e "$f" ] || continue # an empty folder: the pattern matched nothing
if ! grep -q '^ntp server' "$f"; then
basename "$f"
missing=1
fi
done
exit "$missing"
${1:-} is $1, or empty when there isn’t one. This is about as far as a Bash script should go: once it needs
to parse configs properly, keep a list of results, or talk to devices, that’s a job for Python
(Python 101).
5 check: run it, then prove it
$ make check T=7.2when it's right, you'll see
╭─ task 7.2 · audit the configs
│ ✓ audit.sh on the practice folder files/configs: lists chi leaf2.cfg, nyc-leaf2.cfg, exit code 1 (challenge)
│ ✓ audit.sh on a folder where every config has NTP: lists nothing, exit code 0 (challenge)
│ ✓ audit.sh on a folder it hadn't seen: lists core.cfg, edge one.cfg, exit code 1 (challenge)
│ ✓ audit.sh on an empty folder: lists nothing, exit code 0 (challenge)
│ ✓ audit.sh with no folder: a usage line on stderr, exit code 2 (challenge)
╰─ 5/5 checks passed verified