Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do date math in a bash script on OS X Leopard?

I realize I could whip up a little C or Ruby program to do this, but I want my script to have as few dependencies as possible.

Given that caveat, how does one do date math in a bash script on OS X? I've seen a post (on another site) where someone did the following:

date -d "-1 day"

But this does not seem to work on OS X.

Addendum:

Several people have commented and responded that Ruby, Python, Perl, and the like come standard with OS X. I'm familiar with all three of these languages and could easily write a script that does what I want. As a matter of fact, I already have such a script, written in Ruby.

So perhaps I should clarify what I mean by 'external dependency'. What I mean is, I don't want my bash script to have to call any other script external to it. In other words, I want it to use some utility available in a vanilla installation of OS X and already on the path.

However, it doesn't look like this is possible, so I will have to make due with my external dependency: a Ruby script.

like image 944
Gregory Higley Avatar asked Jan 31 '09 05:01

Gregory Higley


People also ask

How do I create a date in bash?

Bash Date Format MM-DD-YYYY To format date in MM-DD-YYYY format, use the command date +%m-%d-%Y . Please observe the upper and lower case letters : %m for month, %d for day and %Y for year.


2 Answers

$ date -v -1d 

-d sets Daylight Savings time flag.

Try man date for more info.

like image 102
Matthew Schinckel Avatar answered Sep 20 '22 23:09

Matthew Schinckel


For example, this OS X date command will add 14 days to the input string 20160826 (not the present time):

date -j -f %Y%m%d -v+14d 20160826 +%Y%m%d 
like image 40
James Toher Avatar answered Sep 22 '22 23:09

James Toher