A Top Option
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 35 of 39.
Challenge
HardAdd a --top N option that shows only the N biggest regions. Keep everything you wrote so far; without --top the report stays the same.
- Move the usage into a function
usagethat printsUsage: report.sh FILE [--top N]to stderr and exits with code1. Call it where the script checked$#. - After saving
file=$1, runshiftso the options are left in"$@". The file check and its exit code2stay. - Set
top="", then loopwhile [[ $# -gt 0 ]]with acase "$1" ininside. For--top, callusagewhen no value follows it, otherwise save the value intopandshift 2. Any other word callsusage. - When
topis set, keep only the first$topsorted lines (head -n "$top") before theprintfloop. - The
Totalline still adds every sale in the file, also the regions--tophides.
Try it: run bash report.sh sales.csv --top 2. It prints:
=== Sales Report ===
North 425
East 405
Total 1350An unknown option prints the usage:
bash report.sh sales.csv --last 2 2>&1; echo "exit $?"
Usage: report.sh FILE [--top N]
exit 1Try it yourself
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter4Strings And Arrays
Slicing StringsTrimming And ReplacingDefault ValuesArraysReading Files Line By LineRecap - CSV Report7Sales Report Project
Project OverviewCheck The Input FileTotals Per RegionSort And FormatA Top OptionSave The ReportPractice on your own: Terminal playground