是否可以在我的代码中放置一个循环?想要为当月的每一天绘制一个区域并保存到文件中。一种方法是硬编码,但这并不好玩,而且由于每个月的天数而变得不切实际。想要加入类似"for each day of mont ..."
或类似"while day < lastDay ...."
#!/bin/bash
# genererar stapeldiagram för nuvarade månad
# sparar fil enl. YYYY-MM-bar.png
# använd tex. crontab 1min.
# om script körs manuellt, sudo
#TODO: argument för specefik månad enl. "$ simple_bar_generator.sh YYYY-MM"
month=$(date +%m)
day=$(date +%d)
monthStr=$(date -d "-$(date +%d) days +1 month" +%B)
year=$(date +%Y)
firstDay=$(date -d "-0 month -$(($(date +%d)-1)) days" +%Y%m%d) #YYYY-MM-DD
lastDay=$(date -d "$firstDay + 1 month - 1 day" +%Y%m%d) #YYYY-MM-DD
source /etc/elmatare.conf
imgPath="/var/www/img/"
tempPath="/tmp/$year-$month-bar.png"
/usr/bin/rrdtool graph $tempPath \
--start $firstDay \
--end $lastDay \
--width 1600 \
--height 400 \
--title 'Förbrukning $monthStr Högmora 4:4' \
--vertical-label 'kWh' \
--alt-y-grid \
--right-axis 1:0 \
--units-exponent 2 \
--color GRID#00000050 \
--color MGRID#00000080 \
while [ $firstDay -le $lastDay ]; do
DEF:tot=$powerDBPath:Tot:AVERAGE:start=YYYYMMDD:end=YYYYMMDD \
CDEF:w=tot,3600,* \
CDEF:energiK=tot,1000,/ \
VDEF:value_sum=energiK,TOTAL \
CDEF:value_area=w,w,-,value_sum,+ \
AREA:value_area#AAAAee \
LINE1:value_area1#000000 \
GPRINT:value_sum:"For testing purposes $day: %0.2lfkWh" \
done
mv $tempPath $imgPath
没有运气!
$ ./simple_bar_generator.sh
./simple_bar_generator.sh: line 31: syntax error near unexpected token `do'
./simple_bar_generator.sh: line 31: `while [ $firstDay -le $lastDay ]; do'
最终循环看起来像:为变量添加索引,rrdtool不接受重用变量。
args=( )
day=$firstDay
i=1
while [[ $day != $(date -d "$lastDay + 1 days" +%Y%m%d) ]]; do
dayStop=$(date -d "$day + 1 days" +%Y%m%d)
args+=(
DEF:tot$i="$powerDBPath:$DS:AVERAGE:start=$day:end=$dayStop"
CDEF:w$i=tot$i,3600,"*"
CDEF:energiK$i=tot$i,1000,/
VDEF:value_sum$i=energiK$i,TOTAL
CDEF:value_area$i=w$i,w$i,-,value_sum$i,+
AREA:value_area$i#AAAAee
LINE1:value_area$i#000000
GPRINT:value_sum$i:"Förbrukning (för testning) $day %0.2lfkWh\n"
)
day=$(date -d "$day + 1 days" +%Y%m%d)
i=$[$i+1]
done
答案 0 :(得分:0)
预先生成你的参数列表,如下所示:
args=( )
day=$firstDay
while [[ $day <= $lastDay ]]; do
args+=(
DEF:tot="$powerDBPath:Tot:AVERAGE:start=YYYYMMDD:end=YYYYMMDD"
CDEF:w=tot,3600,"*"
CDEF:energiK=tot,1000,
VDEF:value_sum=energiK,TOTAL
CDEF:value_area=w,w,-,value_sum,+
"AREA:value_area#AAAAee"
"LINE1:value_area1#000000"
GPRINT:value_sum:"For testing purposes $day: %0.2lfkWh"
)
day=$(date -d "$day + 1 days" +%Y%m%d)
done
...然后,在循环完成后,运行扩展其生成的数组的命令:
rrdtool static-args-here "${args[@]}"