LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Calculating age in days and month in a bash script (http://www.linuxquestions.org/questions/programming-9/calculating-age-in-days-and-month-in-a-bash-script-457379/)

jachba 06-22-2006 05:59 PM

Calculating age in days and month in a bash script
 
I could use some help. I'm working in a bash script and need help with calculating an individual's age in years and months. Calculating the years was simple but months are proving to be a challenge. Thanks in advance for anyone who can help.

archtoad6 06-23-2006 08:13 AM

What does it look like so far? (Hint: use [code] tags).

Also, what will the input look like? Your choice of input format is very important.

How do you define a month? This is not a trivial Q, ask any banker or anyone else calculating interest & principal.

jachba 06-23-2006 12:01 PM

Here's what I have in the section I'm working on. I know that the if statement doesn't work properly (it calculates correctly but still expresses the month category as a negative number) but I'm stuck on how to fix it.

agey=$(($yearnow-$year))
agem=$(($monthnow-$month))

if [ $agem < 0 ]
then
agem=$(($monthnow-$month+12))



else
agem=$(($monthnow-$month))
fi

archtoad6 06-23-2006 12:15 PM

Please re-post using the [code] tags -- code doesn't look right displayed as text.

Also answer the rest of the Q's -- I can't do a thing for you if I don't know what your data looks like or what your variables hold.

homey 06-23-2006 12:42 PM

I think your biggest problem came from this part ....
Code:

if [ $agem < 0 ] instead of this
if [ $agem -lt 0 ]

Code:

#!/bin/bash

read -p "Enter your birth year.  Example: 1900 : " year
read -p "Enter your birht month. Example: 06 " month

yearnow=$(date '+%Y')
monthnow=$(date '+%m')

agey=$(($yearnow-$year))
agem=$(($monthnow-$month))

if [ $agem -lt 0 ] ; then
  agem=$(($monthnow-$month+12))
else
  agem=$(($monthnow-$month))
fi
echo "You are $agey years and $agem months old!"


jachba 06-23-2006 01:37 PM

Thanks, homey. It works fine now.


All times are GMT -5. The time now is 10:36 AM.