#!/bin/ksh # prev_date # # Author: Mike Fleming mike@tauzero.co.uk # # Returns date a specified number of days ago from today # or from specified date (dd mm yyyy) # Returned format yyyymmdd (default) or yymmdd (-y option) # # Options: # # -s Specify a separator character # -y Use 2 digit year # # Used by morefrom and lookfor typeset -i DAY # Declare as a base 10 integer typeset -i MONTH typeset -i YEAR YR=Y DS= USAGE="Usage: prev_date [ -s char ] [ -y ] dateparam\n\n \t-s\tSpecify a separator character\n \t-y\tUse two-digit year\n" while getopts :s:y opt do case $opt in s) DS=$OPTARG;; y) YR=y;; ?) echo "Unknown option $OPTARG" echo $USAGE return 1;; :) echo "No value given for option $OPTARG" echo $USAGE return 1;; *) echo $USAGE return 1;; esac done shift $((OPTIND - 1)) BACK=$1 if [ $# -ne 4 ] then DAY=$(date +%d) MONTH=$(date +%m) YEAR=$(date +%$YR) DS= else DAY=$2 MONTH=$3 YEAR=$4 fi # If we go back past the start of a month, we need to decrement month # and possibly year, and then get the new day - cal gives us the last # day of the month, then need to go back from there. Note we may be # going back more than one month, so we need to decrement a month at # a time until we get to the point where we can subtract BACK from DAY. while [ $DAY -le $BACK ] do if [ $MONTH -eq 01 ] then MONTH=12 YEAR=$((YEAR - 1)) else MONTH=$((MONTH - 1)) fi LASTDAY=$(cal $MONTH $YEAR | tr '\n' ' ' | awk '{print $NF}') DAY=$((DAY + LASTDAY)) done DAY=$((DAY - $BACK)) if [ "$YR" = "Y" ] then printf "%4.4d$DS%2.2d$DS%2.2d" ${YEAR} ${MONTH} ${DAY} else printf "%2.2d$DS%2.2d$DS%2.2d" ${YEAR} ${MONTH} ${DAY} fi