LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   bash script to calculate age difference with loop (http://www.linuxquestions.org/questions/programming-9/bash-script-to-calculate-age-difference-with-loop-946823/)

 shayno90 05-25-2012 09:13 AM

bash script to calculate age difference with loop

I essentially want to calculate this:
"calculate how much beer an 18+ user has drunk statistically (100 liters/year) and print this information for the user."

Not sure how to calculate it i.e. use a loop or other to use the difference in specified age versus user input age, multiply the result, I made an attempt in the last section of code.

Code:

```#!/bin/bash   # This script check's the user's age and if they can legally drink alcohol age=16 lage=18 echo "What age are you?" read uage years=\$[\$age - \$uage] beer=\$[\$years ge \$lage] if [ "\$uage" -ge "\$age" ] ; then     echo -e "You are \$uage and are of legal age to drink alcohol\n" &&     echo -e "You have drank \$ litres of beer since you turned 18 years of age."     exit 1 else     echo -e "You are \$uage and are not of legal age to drink alcohol\n" &&     echo -e "You have to wait \$years years before you can legally drink alcohol" fi while [\$beer]; do         echo " "     let \$beer = \$beer+1 * 100     done if [ "\$uage" == "\$lage" ] ; then     echo " You have drank \$beer litres of beer since you were born" else     echo "You have not drank much beer" fi```

 uhelp 05-25-2012 09:26 AM

Code:

```lage=18 read -p "What is your age? " uage (( beeryears = age - lage  )) (( beer = \$beeryears * 100 )) echo \$beer```

 shayno90 05-25-2012 10:05 AM

Quote:
 Originally Posted by uhelp (Post 4687377) Code: ```lage=18 read -p "What is your age? " uage (( beeryears = age - lage  )) (( beer = \$beeryears * 100 )) echo \$beer```
It only works if the user age is 18 and not if older. I ran this code separately without adding to my own.

-1800

-1800

-1800

 Nominal Animal 05-25-2012 03:40 PM

Code:

```beerperyear=100 legalage=18 read -p "What is your age? " age beer=\$(( (age - legalage) * beerperyear )) if (( beer > 0 )); then     echo "You've drank \$beer liters of beer." else     beer=0     echo "You're not old enough to have drunk beer." fi```
For fractional years (but integral liters of beer) it's easiest to use awk:
Code:

`beer=\$( echo "\$age \$legalage \$beerperyear" | awk '{ printf("%.0f\n", (\$1-\$2)*\$3) }' )`

 grail 05-27-2012 10:07 AM

The bash code example from uhelp has mixed up uage and age variables, a simple change will fix it:
Code:

`(( beeryears = uage - lage  ))`

 shayno90 05-28-2012 07:58 AM

Great that worked!

 All times are GMT -5. The time now is 12:43 PM.