從今天的日期減去 7 天

從今天的日期減去 7 天

這是我的腳本。我需要從今天的日期中減去 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]

答案1

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.  

相關內容