1

我在 bash 中有以下正在进行的脚本。

#!/bin/bash
# usage:
# ./script.sh <iso8601_period>


period_ago() {
    if [[ $1 =~ P(([0-9]+)M)?([0-9]+)D ]]; then
        local months=${BASH_REMATCH[2]:-0}
        local days=${BASH_REMATCH[3]}
        date -d "$months months $days days ago" "+%Y/%m/%d"
    fi
}

period="$(period_ago $1)"

max=3
for (( i=0; i <= $max; ++i ))
do
    temp=$i
    if (( ${#temp}  < 2 ))
    then
       temp="0$temp"
    fi

    echo $period/$temp
done

当你运行它时,目前,这将打印:

2019/07/20/00

2019/07/20/01

2019/07/20/02

2019/07/20/03

我试图弄清楚在运行脚本(传递两个参数)时是否可以做这样的事情,它会给我两个 ISO8601 期间之间的日期,在这种情况下是 100 天前和 99 天前?

./script P100D P99D

2019/07/20/00

2019/07/20/01

2019/07/20/02

2019/07/20/03

2019/07/21/00

2019/07/21/01

2019/07/21/02

2019/07/21/03

4

1 回答 1

1

以 period_ago 函数为基础,并在其上打印“最大”行的循环已经开发:

period_ago {
    ...
}

start=$(period_ago $1)
end=$(period_ago $2)
max=3

d=$start
until [[ $d > $end ]] ; do

# Original Loop to max.
   for (( i=0; i <= $max; ++i )) 
   do
    temp=$i
    if (( ${#temp}  < 2 ))
    then
       temp="0$temp"
    fi

    echo $d/$temp
  done
# Bump to next date
  d=$(date -d "$d tomorrow" +'%Y-%m-%d')

done

更紧凑的版本

start=$(period_ago $1)
end=$(period_ago $2)
max=3

d=$start
until [[ $d > $end ]] ; do

# Original Loop to max.
   for (( i=0; i <= $max; ++i )) ; do
       printf "%s/%02d\n" $d $i
   done
# Bump to next date
  d=$(date -d "$d tomorrow" +'%Y/%m/%d')

done

于 2019-10-28T12:10:56.243 回答