Menu
CoddyTech

Config Checker

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 38 of 39.

challenge icon

Challenge

Hard

Write check.sh, which reads a config file of key=value lines and reports which required keys are missing.

  1. The first argument is the config file and every argument after it is a required key. With fewer than two arguments, print Usage: check.sh FILE KEY... to stderr and exit 1. When the file does not exist, print Error: FILE not found to stderr, with the name in place of FILE, and exit 2.
  2. Read the file line by line and count the lines from 1. Skip empty lines and lines that start with #.
  3. A line without = is broken: print Bad line N: TEXT to stderr, with its line number and the whole line.
  4. In any other line, the key is the text before the first = and the value is everything after it. A key counts as set only when its value is not empty.
  5. For each required key, in the order of the arguments, print KEY: ok or KEY: missing.
  6. Last, print Missing: M with the number of missing keys. Exit 1 when M is more than 0, otherwise exit 0.

Try it with app.conf, where user is only in a comment and name has no value:

bash check.sh app.conf host port user name 2>&1; echo "exit $?"
Bad line 7: listen 9000
host: ok
port: ok
user: missing
name: missing
Missing: 2
exit 1

When every key is set, the script exits 0. Here 2>/dev/null hides the bad line:

bash check.sh app.conf host mode 2>/dev/null; echo "exit $?"
host: ok
mode: ok
Missing: 0
exit 0

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground