lightweight
lightweight

Reputation: 3327

function with a variable ksh like in js

in java script, one can write a function as

function divideByThree(number) {
    return number / 3;
};

console.log(divideByThree(10));

which gives the output of 3.33333....

how do I write the same thing in ksh?

I tried this:

divideByThree(number) {
    number / 3;
};

echo divideByThree(10);

but got this:

-ksh: .: syntax error: `(' unexpected

Upvotes: 0

Views: 66

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754730

divideByThree() {
    echo $(( $1 / 3.0 ))
}

divideByThree 10
echo $(divideByThree 10)
result=$(divideByThree 10)
echo $result

Bash does not support floating point arithmetic; Korn shell does. If you omit the .0 from 3.0, the division is integer division and the result is therefore 3. The return statement returns a status value; you generally use echo to get a value for capture in a variable, etc.

Upvotes: 2

Related Questions