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

前端 未结 17 1372
谎友^
谎友^ 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:13

    Thanks for the help everyone, but since i'm on HP-UX (after all: the more you pay, the less features you get...) i've had to resort to perl:

    perl -e '@T=localtime(time-86400);printf("%02d/%02d/%04d",$T[3],$T[4]+1,$T[5]+1900)' | read dt
    
    0 讨论(0)
  • 2020-12-04 22:17

    You have atleast 2 options

    1. Use perl:

      perl -e '@T=localtime(time-86400);printf("%02d/%02d/%02d",$T[4]+1,$T[3],$T[5]+1900)'
      
    2. Install GNU date (it's in the sh_utils package if I remember correctly)

      date --date yesterday "+%a %d/%m/%Y" | read dt
      echo ${dt}
      
    3. Not sure if this works, but you might be able to use a negative timezone. If you use a timezone that's 24 hours before your current timezone than you can simply use date.

    0 讨论(0)
  • 2020-12-04 22:19

    For Hp-UX only below command worked for me:

    TZ=aaa24 date +%Y%m%d

    you can use it as :

    ydate=`TZ=aaa24 date +%Y%m%d`

    echo $ydate

    0 讨论(0)
  • 2020-12-04 22:23

    You can use GNU date command as shown below

    Getting Date In the Past

    To get yesterday and earlier day in the past use string day ago:

    date --date='yesterday'

    date --date='1 day ago'

    date --date='10 day ago'

    date --date='10 week ago'

    date --date='10 month ago'

    date --date='10 year ago'

    Getting Date In the Future

    To get tomorrow and day after tomorrow (tomorrow+N) use day word to get date in the future as follows:

    date --date='tomorrow'

    date --date='1 day'

    date --date='10 day'

    date --date='10 week'

    date --date='10 month'

    date --date='10 year'

    0 讨论(0)
  • 2020-12-04 22:23

    I have shell script in Linux and following code worked for me:

    #!/bin/bash
    yesterday=`TZ=EST+24 date +%Y%m%d` # Yesterday is a variable
    mkdir $yesterday # creates a directory with  YYYYMMDD format
    
    0 讨论(0)
  • 2020-12-04 22:24

    If you are on a Mac or BSD or something else without the --date option, you can use:

    date -r `expr \`date +%s\` - 86400` '+%a %d/%m/%Y'
    

    Update: or perhaps...

    date -r $((`date +%s` - 86400)) '+%a %d/%m/%Y'
    
    0 讨论(0)
提交回复
热议问题