Recap - Unit Converter
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 5 of 39.
Challenge
MediumWrite 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" ].
- If the script does not get exactly 2 arguments, print
Usage: convert.sh NUMBER UNITto stderr and exit with code1. - If the unit is
h(hours), printN h = M min, where M is N times 60. - If the unit is
kg, printN kg = M g, where M is N times 1000. - If the unit is
km, printN km = M m, where M is N times 1000. - For any other unit, print
Unknown unit: UNITto stderr and exit with code2.
A successful conversion ends with exit code 0.
Try it: run bash convert.sh 3 h. It prints:
3 h = 180 minThen run bash convert.sh 5 lb; echo "exit $?". It prints:
Unknown unit: lb
exit 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