How do I get the bash date script to return a day of the week relative to a non-current time?
Well with bash it can be done with some loop (e.g. get the date you want to use as a reference into a variable in Unix %s format than decrement it with 24*60*60 check if its Sunday, and print it if it's true...)
Or you can set up something like this with awk
awk -v BASEDATE="2011 02 02" -v DIW="Sun" -v BEF="2" 'BEGIN { ct=BASEDATE " 00 00 00" ct=mktime(ct) while (strftime("%a",ct) != DIW) { ct-=24*60*60 } ct-=BEF*24*60*60 print strftime("%Y-%m-%d %a",ct) }'
You can see it in action here. Almost. As ideone (which I adore) does not allow passing command line variables to gawk
(or I was lazy to figure it out ;-)), I had to embed them to the BEGIN
block too.
If you want to you can convert the above to a datecalc.awk
(with !#/usr/bin/gawk -f
script which uses ARGV[n]
variables instead of -v
supplied ones so you can call it easily from your shell scripts.
This is pretty easy to do if you have libfaketime installed.
export LD_PRELOAD=/usr/lib/libfaketime.so.1$ FAKETIME='2012-02-01 00:00:00' date --d='last sunday'Sun Jan 29 00:00:00 EST 2012
You can chain it by setting FAKETIME dynamically. This will get messy, but will work:
$ FAKETIME=$(FAKETIME='2012-02-01 00:00:00' date --d="last sunday" '+%Y-%m-%d %H:%M:%S') date --d="-2 days"Fri Jan 27 00:00:00 EST 2012