CIT052 Index > Processing Command-Line Options

Processing Command-Line Options

Write a script named in the form lastname_firstname_optcalc.sh 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.

./optcalc.sh -x 3 -o add -y 5
8

./optcalc.sh -y 2 -x 15 -o sub
13

./optcalc.sh -o mul -x 12 -y 144
1728

./optcalc.sh -o div -y 4 -x 1892
473

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

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

Pseudocode

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 ]]
then
	if $x isn't null and $y isn't null and $operator isn't null
	then
		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"
	else
		give Usage: message describing the script options
	fi
fi

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 lastname_firstname_optcalc.sh, and upload it to Moodle.