Menu
CoddyTech

Recap - CSV Report

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

challenge icon

Challenge

Hard

Write report.sh, which reads an orders CSV and prints a report with a total for each row and a grand total.

bash report.sh FILE [CURRENCY]: FILE is a CSV whose first line is the header item,qty,price. CURRENCY is optional and defaults to USD.

  • With no arguments, print Usage: report.sh FILE [CURRENCY] to stderr and exit 1.
  • If FILE does not exist, print No such file: FILE to stderr and exit 2.
  • Otherwise print Report: NAME, where NAME is the file name without its folder and without .csv, in uppercase.
  • Then, for each row after the header, print ITEM: QTY x PRICE = LINE, where LINE is QTY times PRICE.
  • Then print Items: N (the number of rows) and Total: SUM CURRENCY (the sum of every LINE). A file with only the header prints Items: 0 and a total of 0.

Collecting the item names in an array gives you N with ${#items[@]}. Read the file with a while loop that has the file sent into it, so the total is still set after the loop.

Try it: run bash report.sh orders.csv. It prints:

Report: ORDERS
pens: 3 x 2 = 6
notebooks: 2 x 5 = 10
ink: 4 x 7 = 28
Items: 3
Total: 44 USD

Then run bash report.sh orders.csv EUR: the last line becomes Total: 44 EUR. bash report.sh nope.csv prints No such file: nope.csv and exits 2.

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground