Shell-Script

從今天的日期減去 7 天

  • May 3, 2019

這是我的腳本。我需要從今天的日期中減去 7 天並在文件名中使用它。我正在使用 Mac。

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

當我執行這個 .sh 腳本時,我得到了這個:

$ /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]

BSD date需要不同的語法:

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

在我的 FreeBSD 上man date包括:

-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.  

引用自:https://unix.stackexchange.com/questions/361758