Menu
CoddyTech

A Top Option

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

challenge icon

Challenge

Hard

Add a --top N option that shows only the N biggest regions. Keep everything you wrote so far; without --top the report stays the same.

  1. Move the usage into a function usage that prints Usage: report.sh FILE [--top N] to stderr and exits with code 1. Call it where the script checked $#.
  2. After saving file=$1, run shift so the options are left in "$@". The file check and its exit code 2 stay.
  3. Set top="", then loop while [[ $# -gt 0 ]] with a case "$1" in inside. For --top, call usage when no value follows it, otherwise save the value in top and shift 2. Any other word calls usage.
  4. When top is set, keep only the first $top sorted lines (head -n "$top") before the printf loop.
  5. The Total line still adds every sale in the file, also the regions --top hides.

Try it: run bash report.sh sales.csv --top 2. It prints:

=== Sales Report ===
North        425
East         405
Total       1350

An unknown option prints the usage:

bash report.sh sales.csv --last 2 2>&1; echo "exit $?"
Usage: report.sh FILE [--top N]
exit 1

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground