Question

How can I have the right result from this bash script?

#!/bin/bash
echo $(( 1/2 ))

I get 0 as result! So I tried to use these but without success:

$ echo $(( 1/2.0 ))
bash: 1/2.0 : syntax error: invalid arithmetic operator (error token is ".0 ")
$ echo $(( 1.0/2 ))
bash: 1.0/2 : syntax error: invalid arithmetic operator (error token is ".0/2 ")
Était-ce utile?

La solution

is not the right tool alone to use floats, you should use with it :

bc <<< "scale=2; 1/2"
.50

If you need to store the result in a variable :

res=$(bc <<< "scale=2; 1/2")
echo $res

Autres conseils

I once stumbled on a nice piece of code, which is somewhat utilizing suggestion sputnick made, but wraps it around a bash function:

function float_eval()
{
    local stat=0
    local result=0.0
    if [[ $# -gt 0 ]]; then
        result=$(echo "scale=$float_scale; $*" | bc -q 2>/dev/null)
        stat=$?
        if [[ $stat -eq 0  &&  -z "$result" ]]; then stat=1; fi
    fi
    echo $result
    return $stat
}

Then, you can use it as:

c=$(float_eval "$a / $b")
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top