Helpful Information
 
 
Category: UNIX Help
need to find previous month from DATE

I am using korn shell and need to find the previous month.

I am able to find the current month by doing:
x=`date +%b`

Is it possible to get the previous month based on the DATE?

Thanks.

#!/bin/ksh

getNextMonth() {
aMonth=$(echo $1 | cut -c1-3); yr=$(echo $1 | cut -c4-)
months=$(cal $yr | grep "[A-Z][a-z][a-z]")

i=1; n=$(for mon in $months; do [[ "$mon" = "$aMonth" ]] && echo $i || (( i += 1 )); done)
[[ "$n" -eq 1 ]] && n=12 && (( yr -= 1 )) || (( n -= 1 ))
echo "$(echo $months | cut -d" " -f$n)$yr"
}
# test previous month function -------------------------------------
for mmmdd in May2004 Dec2004 Jan2004 Mar2004 Aug2004 Jan2009
do
echo "in = $mmmdd \nout = $(getNextMonth $mmmdd)"
done










privacy (GDPR)