In a unix shell, how to get yesterday's date into a variable?

前端 未结 17 1434
谎友^
谎友^ 2020-12-04 21:51

I\'ve got a shell script which does the following to store the current day\'s date in a variable \'dt\':

date \"+%a %d/%m/%Y\" | read dt
echo ${dt}
         


        
17条回答
  •  臣服心动
    2020-12-04 22:31

    Though all good answers, unfortunately none of them worked for me. So I had to write something old school. ( I was on a bare minimal Linux OS )

    $ date -d @$( echo $(( $(date +%s)-$((60*60*24)) )) )
    

    You can combine this with date's usual formatting. Eg.

    $ date -d @$( echo $(( $(date +%s)-$((60*60*24)) )) ) +%Y-%m-%d
    

    Explanation : Take date input in terms of epoc seconds ( the -d option ), from which you would have subtracted one day equivalent seconds. This will give the date precisely one day back.

提交回复
热议问题