Menu
CoddyTech

Save The Report

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

challenge icon

Challenge

Hard

Add an --out FILE option that also saves the report to a file, and end every run with a summary line. Keep everything you wrote so far.

  1. Change the usage line to Usage: report.sh FILE [--top N] [--out FILE].
  2. Add an --out branch to the case: like --top, it calls usage when no value follows, otherwise it saves the value in a variable out (start it as out="") and runs shift 2.
  3. Move the lines that print the report (the title, the region lines and the Total line) into a function named report.
  4. When out is set, run report | tee "$out". tee copies its input to the screen and into the file named after it. Without --out, call report on its own.
  5. Last, print Summary: S sales in R regions, where S is the number of sales (lines after the header) and R is the number of different regions in the file. --top does not change these numbers, and the summary is not saved in the file.

Try it: run bash report.sh sales.csv --top 3 --out top.txt. It prints:

=== Sales Report ===
North        425
East         405
South        335
Total       1350
Summary: 12 sales in 4 regions

Then cat top.txt prints the same lines without the summary:

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

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground