1833877 Members
1630 Online
110063 Solutions
New Discussion

Shell Scripting

 
Jayant Butte
Occasional Contributor

Shell Scripting

Hi,

How do I set a variable say LASTMON to last mondays date like mmddhhmmyyyy 090300002001.

thanks

Jayant
5 REPLIES 5
Thierry Poels_1
Honored Contributor

Re: Shell Scripting

hi,

a very simple solution would be to redirect output of the date command (formatted for your needs) to a file on your system every Monday morning (use the crontab) and refer to this file the rest of the week.
A script to calculate previous Monday would be possible, but not in 2 lines ;)

good luck,
Thierry.
All unix flavours are exactly the same . . . . . . . . . . for end users anyway.
Robin Wakefield
Honored Contributor

Re: Shell Scripting

Hi Jayant,

Here's a perl script to do what I think you want, for any day in the previous week.

#!/opt/perl5/bin/perl

# define days of the week
%DOW=qw(Sun 0 Mon 1 Tue 2 Wed 3 Thu 4 Fri 5 Sat 6);

# read the day you require
$LASTDAY=$ARGV[0];

# get today's day
$NOW=(localtime())[6];

# calculate number of days to count back to last week
$DAYSBACK=$NOW+7-$DOW{$LASTDAY};

# convert to seconds
$SECSBACK=$DAYSBACK*86400;

# convert to epoch time
$THEN=time()-$SECSBACK;

# get the MDY
($month,$day,$year)=(localtime($THEN))[4,3,5];

# and print it
printf ("%02d%02d0000%04d\n",$month+1,$day,1900+$year);


So run it by typing:

/usr/local/bin/script [Sun|Mon|...] e.g.

/usr/local/bin/script Wed
090500002001

Rgds, Robin.
Carlos Fernandez Riera
Honored Contributor

Re: Shell Scripting

For fun (based on cal and date):
y=2001
for i in 1 2 3 4 5 6 7 8 9 10 11 12
do
cal $i $y
done | awk 'BEGIN {i=1;m=0}
$0 ~ y { m++; next}
$1 =="S" { next}
substr ($0,4,2) == " " { next}
$0 == ""{next}
{ printf "L[%d]=%02d%02d%02d\n",i++,substr($0,4,2),m,y}' y=$y >/tmp/88.1
. /tmp/88.1
echo ${L[$(date +"%W")]}

unsupported
Carlos Fernandez Riera
Honored Contributor

Re: Shell Scripting

Run it as ksh
unsupported
A. Clay Stephenson
Acclaimed Contributor

Re: Shell Scripting

Hi:

Whenever I need to do anything date related, I always turn to Julian Dates (~ the number od days since 01/01 4000 B.C.E.); this routine will work for you across year boundaries, leap years, ...

#!/usr/bin/sh

PROG=$0
if [ $# -lt 1 ]
then
echo "Usage: ${PROG} prev_dayofweek" >&2
echo " prev_dayofweek (0 - Sun; 6 - Sat)" >&2
exit 1
fi
DESIRED_WKDAY=$1
shift
TODAY_JDATE=`caljd.sh`
TODAY_WKDAY=`caljd.sh -w`
OFFSET=$((${TODAY_WKDAY} - ${DESIRED_WKDAY}))
if [ ${OFFSET} -le 0 ]
then
OFFSET=$((${OFFSET} + 7))
fi
JDATE=$((${TODAY_JDATE} - ${OFFSET}))
caljd.sh ${JDATE}
STAT=$?
exit ${STAT}

Use it like this:

prevdayofwk.sh 6
It will return '09 08 2001'; if you like you can pipe that output through tr -d ' ' to strip the spaces
e.g. prevdayofwk.sh 6 | tr -d ' '
would result in '09082001'.

I've attached the caljd.sh which is the script which calculate julian dates and does the reverse operation as well.

Regards, Clay
If it ain't broke, I can fix that.