Tag Archives: logarithms

log2 in bash

Turns out bash supports enough arithmetic operators to implement lg() just as you might in some real language:

function log2 {
    local x=0
    for (( y=$1-1 ; $y > 0; y >>= 1 )) ; do
        let x=$x+1
    echo $x

z=$(log2 64)

I had a somewhat valid reason to want to do this. The one thing that continually gets me when I try to do dumb things like this is when to use the raw variable name and when to use the dollar sign. Yes, the semantics are well-defined, but my perl habits run deep. Similarly, in ruby, all my variables are global.