1
#!/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

1
  • shellcheck helpfully points out that you shouldn't use $ on the left-hand side of an assignment. Commented Jul 25, 2016 at 20:29

2 Answers 2

4

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'.

Sign up to request clarification or add additional context in comments.

Comments

1
#!/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

}

calc 6 + 5

Figured out! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.