bashshellunix

expr displaying the expression rather than solving it


Here is my shell script,

#! /bin/sh
# basic calculator
echo "Please input your choice"
printf " 1.Addition \n 2.SUbstraction \n 3.Multiplication \n 4.Division\n"
read choice
case "$choice" in
    1) echo "Enter number 1:";read n1;echo "Enter number 2:";read n2;t=$(expr "$n1"+"$n2");echo "$n1+$n2=$t";;
    2) echo "Enter number 1:";read n1;echo "Enter number 2:";read n2;t='expr $n1-$n2';echo "$n1-$n2=$t";;       
    3) echo "Enter number 1:";read n1;echo "Enter number 2:";read n2;t='expr $n1\*$n2';echo "$n1*$n2=$t";;
    4) echo "Enter number 1:";read n1;echo "Enter number 2:";read n2;t='expr $n1/$n2';echo "$n1/$n2=$t";;
esac

Here is my output,

Script started on Sunday 08 November 2015 12:05:21 PM IST
Please input your choice
 1.Addition 
 2.SUbstraction 
 3.Multiplication 
 4.Division
1
Enter number 1:
5
Enter number 2:
6
5+6=5+6

The problem is that my expr isnt actually solving the expressions


Solution

  • In some versions of expr it's recommended to use shell arithmetic instead:

    $ echo $((5+6))
    11
    $ echo $((5>=6))
    0
    

    Using shell arithmetic using spaces to separate ints is not necessary if desired.

    The expr utility makes no lexical distinction between arguments which may be operators and arguments which may be operands. An operand which is lexically identical to an operator will be considered a syntax error.

     The syntax of the expr command in general is historic and inconvenient.
     New applications are advised to use shell arithmetic rather than expr