Simple math statements in bash in a for loop


Question

I'm quite new to bash scripting and usually avoid it all costs but I need to write a bash script to execute some simple things on a remote cluster. I'm having problems with a for loop that does the following:

for i in {1..20}
do
    for j in {1..20}
    do
        echo (i*i + j*j ) **.5  <--- Pseudo code!
    done
done

Can you help me with this simple math? I've thrown $'s everywhere and can't write it properly. If you could help me understand how variables are named/assigned in bash for loops and the limitations of bash math interpretation (how do you do the square root?) I'd be very grateful. Thanks!

1
6
12/4/2009 11:03:18 PM

Accepted Answer

Here's a decent solution:

for i in {1..20}
do
   for j in {1..20}
   do
       echo "scale = 3; sqrt($i*$i + $j*$j)" | bc
   done
done

Output will be:

1.414
2.236
3.162
2.236
[...etc...]
8
12/4/2009 11:17:51 PM

Arithmetic expansion needs $((...)) notation, so something like:

echo $((i*i + j*j))

However, bash only uses integers so you may need to use an external tool such as dc.

E.g.

dc -e "18k $i $i * $j $j * + v p"

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon