开发者

Get the last day of the last month in csh?

开发者 https://www.devze.com 2022-12-24 05:36 出处:网络
How do you get the last day of the last month in csh? Here is the code so far.The cal command below almost works if you execute it from the (FreeBSD sh) command line, but I\'m having trouble escaping

How do you get the last day of the last month in csh?

Here is the code so far. The cal command below almost works if you execute it from the (FreeBSD sh) command line, but I'm having trouble escaping it properly to run within a script. By almost work, I mean it returns 31, when the last day of February 2010 is 28.

#!/bin/csh
set lastdayoflastmonth=`cal `date '+%m'` `date '+%Y'` | grep . | fmt -1 | tail -1`
echo $lastdayoflastmonth

To be clear:

  • If today is March 26th 2010, it should return the number 28, which is the last day of the February 2010.

  • If today is July 1st 2010, it should开发者_开发技巧 return the number 30, which is the last day of June 2010.

Update: working answer received from Joshua Smith in comments below: date -v31d -v-1m '+%d' Thank you!


Just use the date command:

date -v31d +'%a'

will give you the date name of the last day of the current month

for next month:

date -v31d -v+1m +'%a'

If you want the previous month:

date -v31d -v-1m +'%a'

-- EDIT: commenter has question about GNU Date ---

If you are using gnu date (the above uses BSD date) you can use the -d flag. It's a little more complicated, though (gnu date doesn't do the same thing with month length fuzziness). to get the last day of the month for last month

for the current month:

date -d "$(date -d "next month" +%Y-%m-1) -1 day" +%a

and for next month

date -d "$(date -d "2 months" +%Y-%m-1) -1 day" +%a

for last month:

date -d "$(date +%Y-%m-1) -1 day" +%a


I think (if I recall correctly) that you have to double the backticks (``) when 'nesting' them.

Try (untested):

set lastdayoflastmonth=`cal ``date '+%m'`` ``date '+%Y'`` | grep . | fmt -1 | tail -1`
echo $lastdayoflastmonth


you can shorten your command to omit the grep/fmt. also, there is no need to cram them into one line.

set month=`date '+%m'`
set year=`date '+%Y'`
set lastdaymonth=`cal $month $year  |tr -s " " "\n"|tail -1`

eg

$ tcsh
$ set month="02"
$ set year="2010"
$ set lastdaymonth=`cal $month $year  |tr -s " " "\n"|tail -1`
$ echo $lastdaymonth
28
$ tcsh --version
tcsh 6.17.00 (Astron) 2009-07-10 (i386-intel-linux) options wide,nls,dl,al,kan,rh,color,filec
0

精彩评论

暂无评论...
验证码 换一张
取 消