Menu
CoddyTech

Recap - Unit Converter

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

challenge icon

Challenge

Medium

Write convert.sh, a unit converter that takes a whole number and a unit. Bash does whole-number math inside $(( )): $(( 3 * 60 )) is 180. Inside [ ], = compares two strings: [ "$2" = "h" ].

  1. If the script does not get exactly 2 arguments, print Usage: convert.sh NUMBER UNIT to stderr and exit with code 1.
  2. If the unit is h (hours), print N h = M min, where M is N times 60.
  3. If the unit is kg, print N kg = M g, where M is N times 1000.
  4. If the unit is km, print N km = M m, where M is N times 1000.
  5. For any other unit, print Unknown unit: UNIT to stderr and exit with code 2.

A successful conversion ends with exit code 0.

Try it: run bash convert.sh 3 h. It prints:

3 h = 180 min

Then run bash convert.sh 5 lb; echo "exit $?". It prints:

Unknown unit: lb
exit 2

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground