Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtract days from a date in bash

Tags:

linux

bash

shell

I want to subtract "number of days" from a date in bash. I am trying something like this ..

echo $dataset_date #output is 2013-08-07

echo $date_diff #output is 2   

p_dataset_date=`$dataset_date --date="-$date_diff days" +%Y-%m-%d` # Getting Error
like image 765
Shivam Agrawal Avatar asked Aug 12 '13 06:08

Shivam Agrawal


3 Answers

You are specifying the date incorrectly. Instead, say:

date --date="${dataset_date} -${date_diff} day" +%Y-%m-%d

If you need to store it in a variable, use $(...):

p_dataset_date=$(date --date="${dataset_date} -${date_diff} day" +%Y-%m-%d)
like image 185
devnull Avatar answered Oct 18 '22 21:10

devnull


one liner for mac os x:

yesterday=$(date -d "$date -1 days" +"%Y%m%d")
like image 35
Jeremy Avatar answered Oct 18 '22 19:10

Jeremy


If you're not on linux, maybe mac or somewhere else, this wont work. you could check with this:

yesterday=$(date  -v-1d    +"%Y-%m-%d")

to get more details, you could also see

man date
like image 8
Ankit Bhardwaj Avatar answered Oct 18 '22 21:10

Ankit Bhardwaj