是否可以在代码中放入循环?想要为当前月份的每一天绘制一个区域并保存到文件中。一种方法是硬编码,但这并不有趣,而且由于每个月的天数,这有点不切实际。想要放入类似"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.2lfkWhn"
)
day=$(date -d "$day + 1 days" +%Y%m%d)
i=$[$i+1]
done
预先生成参数列表,如下所示:
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[@]}"