12-29-2008
Quote:
Originally Posted by
Franklin52
A sample to calculate the age with a given date, adapt it to read the date from a file or if you have a different date format.
Code :
#!/bin/sh
echo -n "Enter the birthdate (mm-dd-yyyy): "
The -n option to echo is not standard.
Quote:
Code :
read bdate
bmonth=${bdate:0:2}
That is not sh syntax; it is limited to bash and ksh.
Quote:
Code :
bday=${bdate:3:2}
byear=${bdate:6:4}
cdate=`date +%m-%d-%Y`
cmonth=${cdate:0:2}
cday=${cdate:3:2}
cyear=${cdate:6:4}
Simpler (and POSIX compliant) is:
Code :
eval "$( date "+cyear=%Y cmonth=%m cday=%d" )"
Quote:
Code :
if [[ "$cmonth" -lt "$bmonth" ]] || [[ "$cmonth" -eq "$bmonth" &&
[[ ... ]] is not sh syntax. Use [ .. ] .
Quote:
Code :
"$cday" -lt "$bday" ]]
then
let age=cyear-byear-1
let is not standard. Use POSIX arithmetic:
Code :
age=$(( $cyear - $byear - 1 ))
Quote:
Code :
else
let age=cyear-byear
fi
echo "Age = "$age
Regards
This will run in any POSIX shell:
Code :
## Accept input on command line, or read interactively if none
case $# in
3) bday=$1; bmonth=$2; byear=$3 ;;
*) printf "Enter the birthdate (day month year): "
read bday bmonth byear
;;
esac
## Ensure 2 digits for $bmonth and $bday
case $bmonth in ?) bmonth=0$bmonth;; esac
case $bday in ?) bday=0$bday;; esac
eval "$( date "+cyear=%Y cmonth=%m cday=%d" )"
[ $bmonth$bday -lt $cmonth$cday ] &&
age=$(( $cyear - $byear )) ||
age=$(( $cyear - $byear - 1 ))
echo "Age = $age"
4 More Discussions You Might Find Interesting
1. News, Links, Events and Announcements
Linux has turned 10 . Happy birthday and congrats to the hackers whose labor pains keep giving us new tarballs. (From /. ) (1 Reply)
Discussion started by: mib
1 Replies
2. What is on Your Mind?
A little off topic, as far as not being a critical help issue, but I have been searching about for the OFFICIAL date that is considered the 40th Birthday of UNIX. Some folks mentioned it in March, I think do to a mention on Slashdot of the 40th birthday being this year, but I thought I recall... (1 Reply)
Discussion started by: scotbuff
1 Replies
3. Linux
The Linux kernel was originally created by Linus Torvalds, a Finnish computer science student, and first announced to the world on August 25, 1991-exactly 20 years ago today. At the time, Torvalds described his work as a "hobby" and contended that it would not be "big and professional" like the GNU... (2 Replies)
Discussion started by: itkamaraj
2 Replies
4. What is on Your Mind?
Wish you many many happy returns of the day, stay blessed. (1 Reply)
Discussion started by: Akshay Hegde
1 Replies