1

Create a date in the future for use in Bash scripts on BSD/Mac OSX

 2 years ago
source link: https://ma.ttias.be/create-date-future-bash-scripts-bsd-mac-osx/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Create a date in the future for use in Bash scripts on BSD/Mac OSX

Mattias Geniar, May 14, 2020

Follow me on Twitter as @mattiasgeniar

Annoyingly, the date command differs vastly between Linux & BSD systems. Mac, being based on BSD, inherits the BSD version of that date command.

It took me longer to admit to figure out how to set a date in the future using the date command on a Mac. It requires this arcane syntax.

EXPIRATIONDATE=$(date -j -f "%a %b %d %T %Z %Y" "`date -v+12H`" "+%Y-%m-%dT%H:%M:00")

The above takes “now + 12 hours” as the new date, and formats it as "+%Y-%m-%dT%H:%M:00" - the last parameter.

The -f flag indicates how to parse the date format supplied by the middle parameter.

To get a date in the future, you use the -v command and supply the desired date shift:

date -v+12H

This generates a new date 12 hours into the future. To supply multiple shifts, repeat the -v parameter.

date -v+12H -v-1d -v+10M

Which does: + 12 hours, -1 day, + 10 minutes.

The long command at the top outputs this:

2020-05-15T08:37:00

I hope I won’t have to Google this again!


Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK