我在 Windows 批处理脚本中编写了以下逻辑,我需要在 Unix 中复制相同的逻辑。
# Calculating Yesterday's Date
for /F "tokens=1-4 delims=/- " %%a in ('date/T') do set DY=%%c
for /F "tokens=1-4 delims=/- " %%a in ('date/T') do set MON=%%b
for /F "tokens=1-4 delims=/- " %%a in ('date/T') do set /a YEAR=%%d
if [ $DY=="08" ]; then DAY=8 fi
if [ $DY=="09" ]; then DAY=9 fi
if [ $MON=="08" ]; then MONTH=8 fi
if [ $MON=="09" ]; then MONTH=9 fi
if [ $DY -ne "08" ]; then if [ $DY -ne "09" ]; then DAY=%DY% fi fi
if [ $MON -ne "08" ]; then if [ $MON -ne "09" ]; then MONTH=%MON% fi fi
PREVDAY=%DAY%-1
PREVMONTH=%MONTH%-1
PREVYEAR=%YEAR%-1
ds=%YEAR%_%MONTH%_%PREVDAY%-
if [ %DAY%==1 ]; then if [ %PREVMONTH%==1 ] then ds=%YEAR%_%PREVMONTH%_31- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==2 ] then ds=%YEAR%_%PREVMONTH%_28- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==3 ] then ds=%YEAR%_%PREVMONTH%_31- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==4 ] then ds=%YEAR%_%PREVMONTH%_30- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==5 ] then ds=%YEAR%_%PREVMONTH%_31- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==6 ] then ds=%YEAR%_%PREVMONTH%_30- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==7 ] then ds=%YEAR%_%PREVMONTH%_31- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==8 ] then ds=%YEAR%_%PREVMONTH%_31- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==9 ] then ds=%YEAR%_%PREVMONTH%_30- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==10 ] then ds=%YEAR%_%PREVMONTH%_31- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==11 ] then ds=%YEAR%_%PREVMONTH%_30- fi fi
if [ %DAY%==1 ]; then if [ %PREVMONTH%==0 ] then ds=%PREVYEAR%_12_31- fi fi
答案1
怎么样:
date -d "yesterday" "+%y_%m_%d-"
14_07_08
或者对于 4 位数年份:
date -d "yesterday" "+%Y_%m_%d-"
2014_07_08
要将其分配给变量,请使用:
d=$(date -d "yesterday" "+%y_%m_%d-")
然后:
echo "$d"
14_07_08
或者:
echo "Yesterday was $d"
Yesterday was 14_07_08