1826843 Members
4427 Online
109704 Solutions
New Discussion

Shell script with date

 
SOLVED
Go to solution
Rita Li
Frequent Advisor

Shell script with date

I need to write up a small script to find the last Sunday's date, then to find the last Monday's date before this Sunday

#!/bin/sh
day1=`date "+%Y%m%d"`
day2=`date +%w`
if [ $day2 -eq 2 ]; then
sun_day = $day1
else
sun_day=`date +%Y%m%d-$day2|bc`
fi
mon_day=`date +%Y%m%d-$day2-6|bc`
echo $sun_day $mon_day

However what I need is the dates shown in

19-Jul-2006 format

but the command like

echo `date +"%b-""%d-""%Y"`

only can take the date but not a variable like $sun_day

I am a beginner to shell scripting so please render help

Thanks,
Rita
4 REPLIES 4
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Shell script with date

#!/usr/bin/sh
typeset -i PREV_SUN_JD=0
typeset -i MON_B4_JD=0
typeset PREV_SUN_DT=""
typeset MON_B4_DT=""

PREV_SUN_JD=$(caljd.sh -p 1 -x 1 -x 2 -x 3 -x 4 -x 5 -x 6)
PREV_SUN_DT=$(caljd.sh -S "/" ${PREV_SUN_JD})

MON_B4_JD=$((${PREV_SUN_JD} - 6))
MON_B4_DT=$(caljd.sh -S "/" ${MON_B4_DT})

echo "Last Sunday was ${PREV_SUN_DT} \c"
echo "and the Monday before that was \c"
echo "${MON_B4_DT}"
------------------------------------

This will work across month and year boundaries.

Now download the attached caljd.sh; make it executable; and install somewhere in your PATH. Invoke as caljd.sh -u to figure out how this works and for many examples.


If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Shell script with date

Oops, I'm stupid; this line:
MON_B4_DT=$(caljd.sh -S "/" ${MON_B4_DT})
should obviously be:
MON_B4_DT=$(caljd.sh -S "/" ${MON_B4_JD})

If it ain't broke, I can fix that.
Hein van den Heuvel
Honored Contributor

Re: Shell script with date

Using perl...

The 6th element returned by localtime is the 'day in the week' where Sunday is 0.

So last sunday is now minus $wday

And the monday before that is 6 less still.

Multiply by the number of seconds in a day, subtract from teh current time in seconds and hope that the clock does not strike midnite while doing this...

---- Monday_b4_last_Sunday.pl -----
my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );

$wday = (localtime)[6];
$b4 = time - 86400 * ( 6 + $wday ) ;
($mday,$mon,$year) = (localtime($b4))[3,4,5];
printf "%02d-%s-%d\n", $mday, $abbr[$mon], $year + 1900;

#perl Monday_b4_last_Sunday.pl
10-Jul-2006

hth,
Hein.

Hein van den Heuvel
Honored Contributor

Re: Shell script with date

Same thing, with timing window closed.

use strict;
my @abbr = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my ($now,$b4,$mday,$mon,$year);
$now = time;
$b4 = $now - 86400 * ( 6 + (localtime($now))[6] ) ;
($mday,$mon,$year) = (localtime($b4))[3,4,5];
printf "%02d-%s-%d\n", $mday, $abbr[$mon], $year + 1900;



btw.. I cut & pasted most of this code straight from

http://search.cpan.org/dist/perl/pod/perlfunc.pod

Hein.