0

I am learning bash scripting and currently having trouble with an if statement inside a function. The following code returns two errors; both of which reference the if and elif conditions and say [: 12000: unary operator expected.

function calculateBonus {
    # If the sales figure is greater than 1 million, bonus is £1500
    if [ $1 >= 1000000 ]
    then
        bonus=1500
    # If greater than 100000, bonus is £750
    elif [ $1 >= 100000 ]
    then
        bonus=750
    else
        bonus=0
    fi

    # Return the bonus figure
    return $bonus
}

read sales
bonus=$(calculateBonus $sales)

I have tried using double square brackets, but I'm given a syntax error for some reason. Could someone explain the reason for the error above and for the syntax error when I use [[ some_condition ]] instead of [ some_condition ].

1
  • IIRC the operators for greater equal aren't >= but -ge. Look into man test (test should be the same as [) Commented Feb 14, 2016 at 19:06

2 Answers 2

2

Try this:

function calculateBonus() {
    if (( $1 >= 1000000 )); then
        bonus=1500
    elif (( $1 >= 100000 )); then
        bonus=750
    else
        bonus=0
    fi
}

read sales
calculateBonus "$sales"
echo "Bonus is $bonus"

The (()) is arithmetic evaluation. The function sets the variable bonus which can be used after the function is called. The return in a function does not do what you might think it does (it's an exit code). See also this article about returning values from a function.

This article has a nice discussion on the various test constructs, with examples.

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

1 Comment

Thanks e0k, very comprehensive and answered another question I had
1
function calculateBonus {
# If the sales figure is greater than 1 million, bonus is £1500
if [ $1 -ge 1000000 ]
then
    bonus=1500
# If greater than 100000, bonus is £750
elif [ $1 -ge 100000 ]
then
    bonus=750
else
    bonus=0
fi

}

read sales
calculateBonus $sales
echo $bonus

-ge=>greater than or equal to

see man test which is same as [, help [ directs you to man test

<, > are used for string comparison in bash(dictionary/lexicographical order)

Note: bash also has an advanced if condition operator [[ that has all features of test or [ plus more, see help [[

2 Comments

Ah I see, thanks a lot that's sorted it. Separately from this; when I echo $bonus, it doesn't echo anything. Why is the return value from calculateBonus not assigned to $bonus?
In this instance yeah I can. But if I need to return a value to a variable instead of just echoing it, why would the above not work?

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.