Subtract 7 days from today's date

23,663

With BSD date you need a different syntax:

DATE="$(date -v-7d)"

On my FreeBSD man date includes:

 -v      Adjust (i.e., take the current date and display the result of the  
         adjustment; not actually set the date) the second, minute, hour,  
         month day, week day, month or year according to val.  If val is  
         preceded with a plus or minus sign, the date is adjusted forwards  
         or backwards according to the remaining string, otherwise the  
         relevant part of the date is set.  
Share:
23,663

Related videos on Youtube

mackmama
Author by

mackmama

Updated on September 18, 2022

Comments

  • mackmama
    mackmama almost 2 years

    Here is my script. I need to subtract 7 days from today's date and use it in a file name. I am using a Mac.

    #/bin/bash
    DATE=$(date -d "-7 days")
    echo $DATE
    

    When I run this .sh script, I get this:

    $ /Users/xxxxxxx/xxxxxxxx/dateTest.sh 
    usage: date [-jnRu] [-d dst] [-r seconds] [-t west] [-v[+|-]val[ymwdHMS]] ... 
                [-f fmt date | [[[mm]dd]HH]MM[[cc]yy][.ss]] [+format]
    
    • Eric Renouf
      Eric Renouf about 7 years
      If you really have smart quotes in your script, that would probably mess things up
    • Eric Renouf
      Eric Renouf about 7 years
      Also, what version of date are you using? That syntax works in GNU date, but not BSD date
    • JJoao
      JJoao about 7 years
      Just for the record, in linux (GNU date) this works fine.
    • JdeBP
      JdeBP almost 6 years
      A related question is unix.stackexchange.com/questions/193088 .
  • mackmama
    mackmama about 7 years
    $ bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16) Copyright (C) 2007 Free Software Foundation, Inc.
  • mackmama
    mackmama about 7 years
    DATE=date -v-7d
  • mackmama
    mackmama about 7 years
    I get this error - dateTest.sh: line 2: -v-7d: command not found
  • Eric Renouf
    Eric Renouf about 7 years
    @SkipVV the bash version doesn't matter here, it's all about the date command itself If you're saving it in a variable, you still need the $() syntax, I'll update my answer for that