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!
Another form of integer math expressions in Bash puts the double parentheses on the outside of the entire expression for assignment operations:
As you can see, dollar signs are not needed here (nor inside
$(())
). Also, spaces are permitted around the equal sign.Also, this form can be used in conditionals:
Or you can replace all that with this, of course:
Bash also has a
let
statement:Use double paren to evaluate a variable.
variableA=$((variableB*variableC))
Only for ints though.
Shell math can be done in several ways.
However, this can only handle integer arithmetic. Instead, you can use
bc
:Change
scale
to the number of decimal places desired.Here's a decent solution:
Output will be:
The code
will work if
$X
is an integer. You're trying to take the square root, and I'm not sure if bash's built-in arithmetic will do that. You'll probably be better off using a more powerful calculator tool (likebc
, et al.) for this.