Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple math statements in bash in a for loop

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!

like image 997
physicsmichael Avatar asked Dec 04 '09 23:12

physicsmichael


People also ask

How do I do simple math in bash?

The recommended way to evaluate arithmetic expressions with integers in Bash is to use the Arithmetic Expansion capability of the shell. The builtin shell expansion allows you to use the parentheses ((...)) to do math calculations. The format for the Bash arithmetic expansion is $(( arithmetic expression )) .

Can bash script do math?

Math and arithmetic operations are essential in Bash scripting. Various automation tasks require basic arithmetic operations, such as converting the CPU temperature to Fahrenheit. Implementing math operations in Bash is simple and very easy to learn.

What are $( and $(( )) in bash?

$(...) is an expression that starts a new subshell, whose expansion is the standard output produced by the commands it runs. This is similar to another command/expression pair in bash : ((...)) is an arithmetic statement, while $((...)) is an arithmetic expression. Save this answer.

Is there a for loop in bash?

A bash for loop is a bash programming language statement which allows code to be repeatedly executed. A for loop is classified as an iteration statement i.e. it is the repetition of a process within a bash script. For example, you can run UNIX command or task 5 times or read and process list of files using a for loop.


2 Answers

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"
like image 143
CB Bailey Avatar answered Sep 20 '22 01:09

CB Bailey


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...]
like image 30
dustmachine Avatar answered Sep 17 '22 01:09

dustmachine