Config Checker
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 38 of 39.
Challenge
HardWrite check.sh, which reads a config file of key=value lines and reports which required keys are missing.
- 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 exit1. When the file does not exist, printError: FILE not foundto stderr, with the name in place of FILE, and exit2. - Read the file line by line and count the lines from 1. Skip empty lines and lines that start with
#. - A line without
=is broken: printBad line N: TEXTto stderr, with its line number and the whole line. - 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. - For each required key, in the order of the arguments, print
KEY: okorKEY: missing. - Last, print
Missing: Mwith the number of missing keys. Exit1when M is more than 0, otherwise exit0.
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 1When 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 0Try it yourself
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground