laish138 laish138 - 4 months ago 16
Bash Question

Shell Script : command not found error

#!/bin/bash

calc()
{
n1=$1
op=$2
n2=$3
ans=0

if [ $# -eq 3 ]
then
$ans=$(expr $n1 $op $n2);
echo "$n1 $op $n2 = $ans"
return $ans
else
echo "Needs 3 parameters!"
fi

return;

}


I googled alot but I still can not find the error in my code, I know this is a very simple code but please help me I'm totally new and trying to self study.

The error I get is

line 12: 0=11: command not found


Thank you in advance

Answer

The error is coming the '$ans' on this line

 $ans=$(expr $n1 $op $n2);

Should be

ans=$(expr $n1 $op $n2);

The '$' is evaluating the variable 'ans', as a result instead of assigning the result to your variable 'ans', it is trying to assign the result to '0'.