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

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

    ksh93:

    dt=${ printf "%(%a %d/%m/%Y)T" yesterday; }
    

    or:

    dt=$(printf "%(%a %d/%m/%Y)T" yesterday)
    

    The first one runs in the same process, the second one in a subshell.

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

    If you have Perl available (and your date doesn't have nice features like yesterday), you can use:

    pax> date
    Thu Aug 18 19:29:49 XYZ 2010
    
    pax> dt=$(perl -e 'use POSIX;print strftime "%d/%m/%Y%",localtime time-86400;')
    
    pax> echo $dt
    17/08/2010
    
    0 讨论(0)
  • 2020-12-04 22:25

    If you don't have a version of date that supports --yesterday and you don't want to use perl, you can use this handy ksh script of mine. By default, it returns yesterday's date, but you can feed it a number and it tells you the date that many days in the past. It starts to slow down a bit if you're looking far in the past. 100,000 days ago it was 1/30/1738, though my system took 28 seconds to figure that out.

        #! /bin/ksh -p
    
        t=`date +%j`
        ago=$1
        ago=${ago:=1} # in days
        y=`date +%Y`
    
        function build_year {
                set -A j X $( for m in 01 02 03 04 05 06 07 08 09 10 11 12
                        {
                                cal $m $y | sed -e '1,2d' -e 's/^/ /' -e "s/ \([0-9]\)/ $m\/\1/g"
                        } )
                yeardays=$(( ${#j[*]} - 1 ))
        }
    
        build_year
    
        until [ $ago -lt $t ]
        do
                (( y=y-1 ))
                build_year
                (( ago = ago - t ))
                t=$yeardays
        done
    
        print ${j[$(( t - ago ))]}/$y
    
    0 讨论(0)
  • 2020-12-04 22:25
    $var=$TZ;
    TZ=$TZ+24;
    date;
    TZ=$var;
    

    Will get you yesterday in AIX and set back the TZ variable back to original

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

    If you have access to python, this is a helper that will get the yyyy-mm-dd date value for any arbitrary n days ago:

    function get_n_days_ago {
      local days=$1
      python -c "import datetime; print (datetime.date.today() - datetime.timedelta(${days})).isoformat()"
    }
    
    # today is 2014-08-24
    
    $ get_n_days_ago 1
    2014-08-23
    
    $ get_n_days_ago 2
    2014-08-22
    
    0 讨论(0)
  • 2020-12-04 22:30

    On Linux, you can use

    date -d "-1 days" +"%a %d/%m/%Y"
    
    0 讨论(0)
提交回复
热议问题