Friday, March 23, 2012

dailyLooper bash script


We needed to regenerate some data for the data warehouse so I had to run an extraction script once for each day of the month.

I wrote a simple bash script to make it easier to run a command or other scripts once for every day of a target month and year.

Code can be found below but may also be downloaded from here.

#!/bin/bash
usage(){
    echo "Usage: dailyLooper <year> <month> <script to run>"
    echo "Each date in the given month will be passed into the script in yyyy-mm-dd format"
}


CURRENT_MONTH=$(date +%m)
TARGET_YEAR=$1
TARGET_MONTH=$2

if [ "$#" -lt 3 ]; then
    usage
    exit 1
fi

if [ "$3" = "" ]; then
    SCRIPT="echo"
else
    SCRIPT=$3    
fi

#returns the date yesterday if target month is the current month
#otherwise returns the last date for the target month
lastDayOfMonth(){
    local _year=$1
    local _month=$2   
    if [ $_month -lt $CURRENT_MONTH ]; then
        echo $(date -d "${TARGET_YEAR}-${TARGET_MONTH}-01 + 1 month - 1 day" +%d)
    else
        echo $(date -d "yesterday" +%d)
    fi    
}


main(){
    local _lastDay=$(lastDayOfMonth $TARGET_YEAR $TARGET_MONTH)
    i=1
    while [ "$i" -le $_lastDay ]
    do
        local _date=$(date -d "${TARGET_YEAR}-${TARGET_MONTH}-${i}" +%Y-%m-%d)
        $SCRIPT $_date
        ((i++))
    done #end day of month loop
}

main

I hope you found the post useful. You can subscribe via email or subscribe via a feed reader to get relevant updates from this blog. Have a nice day.

No comments:

Post a Comment