Recap - Toolbox Script
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 15 of 39.
Challenge
MediumWrite tools.sh, a toolbox script. Its first argument names a command, each command is a function, and the arguments after the command go to that function.
bash tools.sh add A Bprints the sum of the two numbers.bash tools.sh count FILEprintsFILE: N lines, where N is the number of lines in FILE. If FILE does not exist, it printsMissing file: FILEto stderr and the script exits 1.bash tools.sh greet NAMEprintsHello, NAME!- With no arguments, the script prints
Usage: tools.sh add|count|greet ARGSto stderr and exits 1. - Any other command prints
Unknown command: CMDto stderr and the script exits 2.
- Open
tools.shand define three functions namedadd,countandgreet. Each one reads its own$1and$2;countreturns 1 when the file is missing. - Below them, check the number of arguments, store the command,
shiftit away, and call the matching function with"$@"from acase. - Save the file.
notes.txtin the file tree has 4 lines to count.
Try it (the comment after each command is what it prints):
bash tools.sh add 7 5 # 12
bash tools.sh greet Ana # Hello, Ana!
bash tools.sh count notes.txt # notes.txt: 4 lines
bash tools.sh count nope.txt # Missing file: nope.txt, exit code 1
bash tools.sh # Usage: tools.sh add|count|greet ARGS, exit code 1
bash tools.sh zip # Unknown command: zip, exit code 2Try it yourself
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground