Menu
CoddyTech

Recap - Toolbox Script

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

challenge icon

Challenge

Medium

Write 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 B prints the sum of the two numbers.
  • bash tools.sh count FILE prints FILE: N lines, where N is the number of lines in FILE. If FILE does not exist, it prints Missing file: FILE to stderr and the script exits 1.
  • bash tools.sh greet NAME prints Hello, NAME!
  • With no arguments, the script prints Usage: tools.sh add|count|greet ARGS to stderr and exits 1.
  • Any other command prints Unknown command: CMD to stderr and the script exits 2.
  1. Open tools.sh and define three functions named add, count and greet. Each one reads its own $1 and $2; count returns 1 when the file is missing.
  2. Below them, check the number of arguments, store the command, shift it away, and call the matching function with "$@" from a case.
  3. Save the file. notes.txt in 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 2

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground