Check The Input File
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 32 of 39.
Challenge
MediumThe report reads the CSV file named by its first argument. Make report.sh check that argument before it prints anything. Keep everything you wrote so far.
- Under the comment, add
set -euo pipefailso the script stops on errors and unset variables. - When the script gets no argument, print
Usage: report.sh FILEto stderr and exit with code1. Check the count with$#: underset -u, reading a missing$1is an error. - Save the first argument in a variable named
file. - When
fileis not an existing file, printError: FILE not foundto stderr, with the name in place of FILE, and exit with code2. - Otherwise print the title
=== Sales Report ===as before.
Try it: run bash report.sh sales.csv. It prints:
=== Sales Report ===Then run the two error paths with 2>&1, so stderr shows up, and echo "exit $?" after them:
bash report.sh 2>&1; echo "exit $?"
Usage: report.sh FILE
exit 1
bash report.sh missing.csv 2>&1; echo "exit $?"
Error: missing.csv not found
exit 2Try 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