Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2) (20 points) Write a Bash shell script named \"calc.sh\" that a. Performs addi

ID: 3872248 • Letter: 2

Question

2) (20 points) Write a Bash shell script named "calc.sh" that a. Performs addition (+), subtraction (), multiplication (x), and integer division () math b. Takes in 2 operands and 1 operator and prints the result. Example: "calc.sh 53" would c. If there are not exactly 3 arguments, or the second argument is not one of the operators in d. If operator is division (/) and second operand is 0, then print error message "error: cannot operations. print "8" and "calc.sh 9/2" would print "4" part (a), or first or third argument is not an integer, print an error message and exit divide by 0" and exit e. Hint: Use case statement

Explanation / Answer

if [ $# -eq 3 ] ; then
op1=$1
op=$2
op2=$3

if [ "$op1" -eq "$op1" ] 2>/dev/null ; then
    f1=0
else
    f1=1
fi
if [ "$op2" -eq "$op2" ] 2>/dev/null ; then
    f2=0
else
    f2=1
fi
if [ $f1 -eq 1 ] ; then
    echo "First value should be number"
    echo "Usage : calc <num1> <op> <num2>"
    exit 1;
fi
if [ $f2 -eq 1 ] ; then
    echo "second value should be a number"
    echo "Usage : calc <num1> <op> <num2>"
    exit 2;
fi

case "$op" in
    "+")
       echo "$op1 + $op2 = `expr $op1 + $op2`"
       ;;
    "-")
       echo "$op1 - $op2 = `expr $op1 - $op2`"
       ;;
    "*")
        echo "$op1 * $op2 = `expr $op1 * $op2`"
       ;;
    "/")
        echo "$op1 / $op2 = `expr $op1 / $op2`"
       ;;
     *) echo "Invalid operator"
esac
else
      echo "Usage : calc <num1> <op> <num2>"
fi

<<'COMMENT'
lenovo@lenovo-Vbox:~/chegg$ ./calc.sh
Usage : calc <num1> <op> <num2>
lenovo@lenovo-Vbox:~/chegg$ ./calc.sh 3
Usage : calc <num1> <op> <num2>
lenovo@lenovo-Vbox:~/chegg$ ./calc.sh 3 +
Usage : calc <num1> <op> <num2>
lenovo@lenovo-Vbox:~/chegg$ ./calc.sh 3 + a
second value should be a number
Usage : calc <num1> <op> <num2>
lenovo@lenovo-Vbox:~/chegg$ ./calc.sh a / 8
First value should be number
Usage : calc <num1> <op> <num2>
lenovo@lenovo-Vbox:~/chegg$ ./calc.sh 4 + 5
4 + 5 = 9
lenovo@lenovo-Vbox:~/chegg$ ./calc.sh 10 - 6
10 - 6 = 4
lenovo@lenovo-Vbox:~/chegg$ ./calc.sh 10 * 6
10 * 6 = 60
lenovo@lenovo-Vbox:~/chegg$ ./calc.sh 10 / 6
10 / 6 = 1
lenovo@lenovo-Vbox:~/chegg$
COMMENT

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote