Recap - CSV Report
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 21 of 39.
Challenge
HardWrite 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: FILEto 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) andTotal: SUM CURRENCY(the sum of every LINE). A file with only the header printsItems: 0and 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 USDThen 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
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 ReportPractice on your own: Terminal playground