BMI Calculator in Bash Shell

I am trying to create a script using the Linux Bash shell to calculate BMI. I know that I'm just doing something stupid, but I can't get it to work. It will not be a separation. You can see where I made a mistake.

     #!/bin/bash
     #==============================================================
     # Script Name: bmicalc
     # By:          mhj
     # Date:        March 25, 2014
     # Purpose:     calculates your bmi from your weight & height
     #===============================================================
     #Get your weight and height
     echo -n "What is your weight in pounds? "
     read weight
     echo -n "What is your height in inches? "
     read height
     #calculate your bmi
     let total_weight=$weight*703
     let total_height=$height*$height
     bmi=$total_weight/$total_height
     echo "Your weight is $weight"
 echo "Your height is $height"
 echo -n "Your BMI is $bmi"
+4
source share
5 answers

You are almost there, you just need more let:

let bmi=$total_weight/$total_height

Alternatives

There are so many ways to have an arithmetic context in a shell. The preferred standard way is the syntax $(( )):

total_weight=$(( $weight * 703 ))

expr (. ) , POSIX sh. ( $[ ], , .)

, . integer RHS :

declare -i weight height bmi total_weight total_height
total_weight=weight*703
total_height=height*height
bmi=total_weight/total_height

let.

(( )).

(( total_weight=weight*703 ))
(( total_height=height*height ))
(( bmi=total_weight/total_height ))

, expr - .

total_weight=$(expr $weight '*' 703) # Have to escape the operator symbol or it will glob expand
total_height=$(expr $height '*' $height) # Also there this crazy subshell

... meh, !

, bash . ( .)

, . , bc, awk .

+2

? ( ) , , let:

echo "Your BMI is $(( (weight * 703) / (height * height) ))"

... , awk :

awk -v weight="$weight" -v height="$height" \
  'BEGIN { printf "%f\n", ((weight * 703) / (height * height)) }'
+1

, ... Bash , . , . bc , .

:

7/3= 2 ( 2.33333333)

7%3= 1

0

, bc:

$ weight=160
$ height=70
$ echo "Your BMI is $(bc <<< "scale=3; ($weight * 703) / ($height * $height)")"
Your BMI is 22.955
$ 

scale=3;reports bcdisplaying up to 3 decimal places. Modify this according to your needs.

0
source

I would use bcfor this. The variable scaledetermines the number of decimal places in the response:

bmi=$(bc <<< "scale=2; $total_weight/$total_height")

Alternatively, you can use -lto load the standard math library, which sets scaleto 20:

bmi=$(bc -l <<< "$total_weight/$total_height")

awk always an option:

bmi=$(awk -v w="$total_weight" -v h="$total_height" 'BEGIN { print w/h }')
0
source

Source: https://habr.com/ru/post/1533434/


All Articles