Frage

my ksh version is not allowed date -d.

The bellow code has problem when current month is January.

#!/bin/ksh

yy=`date +%Y`
mm=`date +%m-1|bc`

[ $mm -lt 1 ] && (mm=12;yy=`expr $yy - 1`)
[ $mm -le 9 ] && mm="0$mm"
getcal=`cal $mm $yy`
last_dd=`echo $getcal|awk '{print $NF}'`
dd1=`echo $getcal|awk '{print $10}'`

first_dd="0$dd1"

echo $yy$mm$last_day
echo $yy$mm$first_day
War es hilfreich?

Lösung

You're using a subshell: any variable changes you make will not survive the subshell exiting:

$ m=5; (m=10); echo $m
5

Use a different grouping construct

[ $mm -lt 1 ] && { mm=12; ((yy -= 1)); }

If you have GNU date, you can do:

$ first_of_this_month=$(date "+%Y-%m-01")
$ date -d "$first_of_this_month - 1 day" "+%Y-%m-%d"
2014-03-31
$ date -d "$first_of_this_month - 1 month" "+%Y-%m-%d"
2014-03-01
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top