January 23, 2011

Shell Script: Adding days to a date input

(image taken from smashingapps.com)

Last week, I spent approximately 2 hours trying to figure out how I could add 1 day to a shell script's date input.
And, this is the solution I came up with:










Here is the code:
#--- pretend this is your date input in YYYYMMDD format (string)
datestring='20110123'

#--- convert string to date
datestamp=`date --date $datestring +%Y%m%d`

#--- get the formatted date input and add one day to it
dateplusone=$((datestamp +1))

echo "The date string is: " $datestring
echo "Date plus one is: " $dateplusone

#--- use it as a log file time stamp
logfile=daily_log_$dateplusone.txt

echo -e "Finally after 2 hours you nailed it! Your log file is:" $logfile "\nTime to grab a cup of coffee and move on to the next task!"

touch $logfile


Hope this helps someone with the same problem :)

3 comments:

  1. crapola! there is still something wrong with the script :D

    ReplyDelete
  2. Just found this page. Try this code out...
    datestamp=`date --date "$datestring +$daycounter days" +%Y-%m-%d`

    This will factor in the end of the month as well :)

    ReplyDelete