CIT052 Index > Processing Command-Line Options

Processing Command-Line Options

Write a script named in the form Your script will implement a simple calculator using command line options. The script will take three command-line parameters: x (a number), y (another number), and o, an operation which is one of add, sub, mul, or div. It will then add, subtract, multiply, or divide x and y, depending on which operator was chosen, and display the result.

Here is sample output from several runs of the program. Your program does not have to give exactly these prompts and error messages, but it must exhibit similar behavior.

./ -x 3 -o add -y 5

./ -y 2 -x 15 -o sub

./ -o mul -x 12 -y 144

./ -o div -y 4 -x 1892

./ -x 3
Usage: ./ -x number -y number -o add|sub|mul|div

./ -x 3 -c bad
-c is an invalid option.


Here is some pseudocode to help you.

Set a variable named error to zero.

Get the options with a while loop as described in the book.
For valid otions, store $OPTARG into a variable named x,
y, or operator as appropriate.
For invalid options, echo an error message and set the
error variable to 1.

if [[ $error != 1 ]]
	if $x isn't null and $y isn't null and $operator isn't null
		use a case statement to calculate the result;
		put it in a variable named result. If
		the operator isn't valid, put the error message
		into result
		echo "$result"
		give Usage: message describing the script options

Note: use $0 in the "Usage" message to get the correct name of the script.

When You Finish

Make sure the script file is named in the form, and upload it to Moodle.