0

I'm learning shell scripting and I'm studying how to use function in the shell script. The script is suppose to run as a basic math calculator with two defined numbers by the user. It's suppose to add, subtract, multiply, and divide. When the script is ran it can't seem to get to the function to produce the results. It stops at line: "1")result=add $num1 $num2 ;; and can't find the command. I'm not sure what I'm missing in my code.

#!/bin/bash

#function definition

function add()
{
    echo $(($num1 + $num2))
}
function subtract()
{
    echo $(($num1 - $num2))
}
function multiply()
{
    echo $(($num1 * $num2))
}
function divide()
{
    echo $(($num1 / $num2))
}

#Main Script
echo "Enter two numbers:"
read num1 num2
echo "Enter 1 for additon, 2 subtraction, 3 multiplication, 4  divison:"
read num3
case "$num3" in
    "1")result=add $num1 $num2 ;;
    "2")result=subtract $num1 $num2 ;;
    "3")result=multiply $num1 $num2 ;;
    "4")result=multiply $num1 $num2 ;;
     * ) echo "You didn't enter 1,2,3,4 for your function." ;;
esac
echo "The result is $result: "
  • 1
    I fixed the shebang and indentation. Please note that you are giving $num1 and $num2 as parameters when calling the functions, but you are not using them as parameters within the functions. Substituting $(($num1 + $num2)) with $(($1 + $2)) etc. would better match the function calls and make your functions independent of the names of the variables used later. As your code is now, you could also write result = $(add foo bar) and it would still return the result of $num1 + $num2. – Dubu Nov 24 '15 at 16:05
3
result=add $num1 $num2

This line is interpreted by the shell as an assignment (result=add), command ($num1) and argument ($num2). That's not what you wanted. To retrieve output of a function, you need command substitution:

result=$(add $num1 $num2)
0

Your functions are not using the values passed to them on the command line, they are using the global variables $num1 and $num2.

To use the passed values, rewrite them like this:

function add()
{
    echo $(($1 + $2))
}

or

function add()
{
    local num1="$1"
    local num2="$2"

    echo $(($num1 + $num2))
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy