0

As pre requirement, I need to fetch last month date in Unix (solaris) csh.

set Lmit_Date=`date --date='1 month ago' +%Y%m%d` 

above command will fetch last month date and working fine in Linux server. But our server is Solaris and mentioned command is not working.

Please can anyone suggest how I can fetch the last month date

Martin Tournoij
  • 26,737
  • 24
  • 105
  • 146
Ashutosh
  • 111
  • 14

3 Answers3

2

The issue is due to the fact you are using a GNU date extension. --date is non standard.

Moreover, due to the fact month lengths are variable, the date displayed by GNU date might be unexpected, to say the least...

For example today is March 31 but "last month" date was March the 2nd according to GNU date:

$ date +%Y%m%d
20160331
$ date --date='1 month ago' +%Y%m%d
20160302

If you still want to either use GNU date on Solaris or find some workarounds, have a look to these replies: https://stackoverflow.com/a/23507108/211665 and https://stackoverflow.com/a/17817087/211665

Community
  • 1
  • 1
jlliagre
  • 29,783
  • 6
  • 61
  • 72
  • *For example today is March the 31 but last month date was March the 2nd according to GNU date* Ooof. That's an inexcusably unclear behavior. I'd hope the questioner is reconsidering his use of GNU date to do that. Note the handwringing over it: https://lists.gnu.org/archive/html/bug-coreutils/2012-08/msg00131.html – Andrew Henle Mar 31 '16 at 10:31
1

You should be able to compile coreutils for your solaris platform, which will provide you with the right date utility. But as coreutils overwrites core utilities as the name says, you may want to install this into a custom path and select the right date command through your special path, say "/opt/coreutils/bin/date".

The other method would be to calculate last month with a symbolic date output split

eval `date +"set YEAR=%Y; set MONTH=%m ;set DAY=%d"`

Now you can operate on "$YEAR", "$MONTH" and "$DAY". For example

let 'MONTH--'
if [ "$MONTH" -eq 0 ]; then MONTH=12; let 'YEAR--'; fi
set Lmit_Date=`date --date "$MONTH$DAY0000$YEAR" +"%Y%m%d"`

kind of. (I'm used to bash so I don't know if let is available here. But there are some other methods to shell calculations. There might be another keyword for csh).

Also you need to take care for number of days per month with the $DAY parameter.

ikrabbe
  • 1,909
  • 12
  • 25
0
function last_day {
  y=`echo $1 | cut -f1 -d "-"`
  m=`echo $1 | cut -f2 -d "-"`
  d=`cal ${m} ${y} | nawk 'NF{A=$NF}END{print A}'`

echo "$y $m $d" | nawk '{printf("%s-%02d-%02d",$1,$2,$3);}'
}           # last_day

last_day 2023-01-01

Will give you: 2023-01-31 in non-GNU Solaris.

access_granted
  • 1,807
  • 20
  • 25