3

Totally new to BASH. Apologies in advance.


Problem

I'd like to add X days to a specific date.


Code

I figured out that date in BASH retrieves the current date.

I also figured out that I can add X days to the current date in the following way,

expiration_date=$ date -v +1d

which gives,

Tue Sep 26 20:28:13 CEST 2017 

which is indeed the date of writing plus X=1 days.


Question

In stead of date in the command line above, I'd like to insert a particular date to which X days will be added, e.g. 20/09/2017.

Don't care about the format of the particular date.

In other words: How do I make the following work,

expiration_date=$ '20/09/2017' -v +1d

Tried this answer, but doesn't do what I want.


Edit: Did not know things are different for OSX.

anubhava
  • 761,203
  • 64
  • 569
  • 643
LucSpan
  • 1,831
  • 6
  • 31
  • 66

2 Answers2

11

You can do this way:

dt='2017-09-20'

date -d "$dt +1 day"
Thu Sep 21 00:00:00 EDT 2017

date -d "$dt +2 day"
Fri Sep 22 00:00:00 EDT 2017

It seems OP is using OSX. You can use date addition this way:

s='20/09/2017'
date -j -v +1d -f "%d/%m/%Y" "$s"

Thu Sep 21 14:49:51 EDT 2017
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Thank you. My terminal shows me this when I do your command: `usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]`. Not sure what to do? – LucSpan Sep 25 '17 at 18:44
  • Are you on OSX? This date command I provided is for `gnu date`. On my OSX I got it using `brew` installer. – anubhava Sep 25 '17 at 18:46
  • 1
    Thank you, it worked! Did not know things are different on OSX. – LucSpan Sep 25 '17 at 18:52
  • Last question. If I want to assign the addition result to a variable and call it, how would I do that? I.e. a correct form of `end=(date -j -v +1d -f "%d/%m/%Y" "$s")`, `echo end`. – LucSpan Sep 26 '17 at 11:16
  • Use `end=$(...)` – anubhava Sep 26 '17 at 11:49
  • I tried that, e.g. `end=$(date -j -v +1d -f "%d/%m/%Y" "$s”)`, but then terminal states `./test.txt: line 5: unexpected EOF while looking for matching `"''`./test.txt: line 6: syntax error: unexpected end of file` – LucSpan Sep 26 '17 at 11:52
  • 1
    Ok, I fumbled around with i.a. white spaces and found that `end=$( date -j -v +30d -f "%d/%m/%Y" "$s") echo $end` works. Thanks. – LucSpan Sep 26 '17 at 12:04
0

You can do something like this:

date -d "Sun Sep 6 02:00:00 IST 2012+10 days"
Matias Barrios
  • 4,674
  • 3
  • 22
  • 49