使用日期值作为 bash 关联数组中的键

Using a date value as a key in a bash associative array

我有一个日期值和一个关联的整数,我想通过我的 bash 脚本将其存储在一个数组中。目前,我只是提出有问题的行,因为我认为问题是本地化的。

chartDate=2014-12-01;
dayTotal=5;

dataArray[${chartDate}]=$dayTotal;

尝试上述操作时,我得到:

line 125: 2014-12-01: value too great for base (error token is "01")

如果我尝试以下任一操作,我会遇到不同的错误:

dataArray["${chartDate}"]=$dayTotal;
dataArray[\""${chartDate}"\"]=$dayTotal;

有什么建议吗?

完整的脚本是:

function getChartData () {


    chartDate=$(chartStartsAt); #$(chartStartAt) returns a date formatted %Y-%m-%d
    echo $chartDate;

    now=`date +%Y-%m-%d`;
    echo $now;

    issueCount=`jq '. | length'  output/json/FullIssueList.json`; #returns an integer

    declare -a dataArray;

    while [ "${chartDate}" \< "${now}" ]
        do 
            #increment chartDate by one day
            chartDate=$(date -j -v +1d -f "%Y-%m-%d" "${chartDate}" +%Y-%m-%d);
            echo $chartDate

            #Get number of records that match that date
            dayTotal=`grep -c "${chartDate}" output/json/FullIssueList.json`;
            echo $dayTotal;

            #Put values in the array
            dataArray[${chartDate}]=$dayTotal;
        done

    for K in "${!dataArray[@]}"; do echo $K --- ${MYMAP[$K]}; done

}

这里是评论中建议的 -uxv 输出,注意上面还有另外 7 或 8 个结果:

+ set -uxv
+ dataArray[${chartDate}]=0
+ '[' 2014-12-06 '<' 2015-01-09 ']'
date -j -v +1d -f "%Y-%m-%d" "${chartDate}" +%Y-%m-%d
++ date -j -v +1d -f %Y-%m-%d 2014-12-06 +%Y-%m-%d
+ chartDate=2014-12-07
+ echo 2014-12-07
2014-12-07
grep -c "${chartDate}" output/json/FullIssueList.json
++ grep -c 2014-12-07 output/json/FullIssueList.json
+ dayTotal=0
+ echo 0
0
+ set -uxv
+ dataArray[${chartDate}]=0
+ '[' 2014-12-07 '<' 2015-01-09 ']'
date -j -v +1d -f "%Y-%m-%d" "${chartDate}" +%Y-%m-%d
++ date -j -v +1d -f %Y-%m-%d 2014-12-07 +%Y-%m-%d
+ chartDate=2014-12-08
+ echo 2014-12-08
2014-12-08
grep -c "${chartDate}" output/json/FullIssueList.json
++ grep -c 2014-12-08 output/json/FullIssueList.json
+ dayTotal=0
+ echo 0
0
+ set -uxv
+ dataArray[${chartDate}]=0
./GetJiraReleaseIssues.sh: line 125: 2014-12-08: value too great for base (error token is "08")

要使用关联数组,您必须首先声明它

declare -A dataArray
#        ^
#    CAPITAL A

如果不这样做,bash 会将数组视为普通数组并尝试将索引解释为数值表达式。