I am trying to write a script I will call calc.sh that does basic calculations using the arguments for the script ( $1, $2 and $3). For instance I'd like to get 2 as result for ./calc.sh 10 / 5
My start goes as this:
if [ $2 -eq "+" ] ; then res=`expr $1 + $3` ; echo "$res" ; fi
But it won't work, I get something like : Line 2 : [ +: an integer expression was expected
NOw That I used == to make the comparison is working fine for all the operations except the division /. The code now is:
if [ $2 == "+" ] ; then res=`expr $1 + $3` ;
elif [ $2 == "-" ] ; then res=`expr $1 - $3` ;
elif [ $2 == "x" ] ; then res=`expr $1 \* $3` ;
elif [ $2 == "/" ] ; then res=`expr $1 \/ $3` ;
else res=`Operación no válida` ;
fi ; echo "$res"
But if I try ./calc.sh 10 / 5
, I will get: "line 4: 10 / 5 : syntax error: invalid arithmetic operator (the error element is "\ 5 ")... Alas as I am typing I'm realising it should be $1 / $3 ...
:)
man test
...-eq
is for numbers, for strings you want=
. – AlexP Nov 14 '16 at 12:15