2

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]
  • 1
    If you really have smart quotes in your script, that would probably mess things up – Eric Renouf Apr 27 '17 at 19:13
  • Also, what version of date are you using? That syntax works in GNU date, but not BSD date – Eric Renouf Apr 27 '17 at 19:15
  • that looks like it might be OSX – Jeff Schaller Apr 27 '17 at 19:23
  • 1
    Just for the record, in linux (GNU date) this works fine. – JJoao Apr 28 '17 at 10:22
  • A related question is unix.stackexchange.com/questions/193088 . – JdeBP Sep 3 '18 at 10:09
5

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.  
  • $ bash --version GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16) Copyright (C) 2007 Free Software Foundation, Inc. – SkipVV Apr 27 '17 at 19:28
  • DATE=date -v-7d – SkipVV Apr 27 '17 at 19:29
  • I get this error - dateTest.sh: line 2: -v-7d: command not found – SkipVV Apr 27 '17 at 19:29
  • @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 – Eric Renouf Apr 27 '17 at 19:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.