Simple math statements in bash in a for loop

2020-06-18 05:43发布

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!

11条回答
何必那么认真
2楼-- · 2020-06-18 06:07

Typically you would use $((1*3)), but your case won't work as bash doesn't support floating point numbers. You'll have to use an external tool like awk, bc or dc: http://mywiki.wooledge.org/BashFAQ/022

查看更多
欢心
3楼-- · 2020-06-18 06:10

with zsh, this will work

for i in {1..20};do
  for j in {1..20};do
     echo $((($i*$i + $j*$j)**.5))
  done
done
查看更多
Summer. ? 凉城
4楼-- · 2020-06-18 06:12

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"
查看更多
Melony?
5楼-- · 2020-06-18 06:15
#!/bin/bash
for i in {1..20}; do
    for j in {1..20}; do
        echo 5k$i $i\* $j $j\*+vp | dc
    done
done
查看更多
啃猪蹄的小仙女
6楼-- · 2020-06-18 06:17

Bash doesn't offer mathematical functions. However, you almost certainly have the korn shell installed. This should work:

#!/bin/ksh

for i in {1..20}
do
    for j in {1..20}
    do
        x=$((sqrt(i*i + j*j)))
        echo "sqrt($i^2 + $j^2) = $x"
    done
done

The beginning of the output is

sqrt(1^2 + 1^2) = 1.41421356237309505
sqrt(1^2 + 2^2) = 2.2360679774997897
sqrt(1^2 + 3^2) = 3.16227766016837933
sqrt(1^2 + 4^2) = 4.12310562561766055
sqrt(1^2 + 5^2) = 5.09901951359278483
sqrt(1^2 + 6^2) = 6.08276253029821969
sqrt(1^2 + 7^2) = 7.07106781186547524
sqrt(1^2 + 8^2) = 8.06225774829854965
sqrt(1^2 + 9^2) = 9.05538513813741663
sqrt(1^2 + 10^2) = 10.0498756211208903
查看更多
放我归山
7楼-- · 2020-06-18 06:19

does your remote cluster only have bash? if not, try and see if you have awk

awk 'BEGIN{
  for(i=1;i<=20;i++){
    for(j=1;j<=20;j++){
       print ( i*i + j*j ) ** 0.5
    }
  }
}'
查看更多
登录 后发表回答