如何优化以下脚本

时间:2016-05-17 15:21:47

标签: bash scripting

此脚本运行查询以获取日期列表,并针对这些日期运行另外两个查询。 然后比较哪一个是较小的数字并将其乘以2。 然后写入文件并对它们求和。 请提出改进​​建议。还检查0个数字。

#!/bin/bash

1>output.txt

today=$(date +"%Y%m%d")
FirstOfTheMonth=$(date -d "--$(($(date +%-d)-1)) day" `enter code here`+"%Y%m%d")

 echo "XXXX activity report on daily and cumulative monthly `enter code here`basis "
 #query that outputs dates to a file
SQL query > list
#for each date I run 2 queries
for i in `cat list`;do
a1=SQL query;
b1=SQL query;
# I compare to find out which one is the smaller number and `enter code here`multiply it by 2

buy=${a1#-}
sell=${b1#-}
echo "XXX report for $yesterday  month = $i "

echo "Buy  $buy"
echo "Sell  $sell"

if [ "$buy" -lt "$sell" ];
then DayNumber=$[buy * 2];
else DayNumber=$[sell * 2];
fi;
#I write all the numbers to a file since I have to sum them
MonthNumber=`awk '{ sum += $1 } END { print sum }' `enter `enter code here`code here`DayNumber$i`
echo "Day Number $DayNumber"
echo "$DayNumber$i $MonthNumber$1 $yesterday" >> DayNumber$i

echo "Day Number since $FirstOfTheMonth $MonthNumber$1"
echo ---------------------------------------------------------------------------------------
done
/usr/bin/mail -s "XXXX report $today" xxx@xxxx.com < `enter code here`output.txt

1 个答案:

答案 0 :(得分:0)

你最有可能获得投票,做到代码大小,缺乏你想要的清晰度,没有努力自己得到这个结果,以及代码可读性的非常基本的错误,可以用网络搜索教程。谷歌有一个你应该阅读的shell风格指南。

如果要将stdout重定向到文件,则可能是自主运行的。这意味着你也应该重定向stderr。 exec &>output.txt

本月的第一天 - 不知道你为什么不这样做 FirstOfTheMonth=$(date +%Y%m1)

为了Pete的缘故,缩进!这让我想要打败脚本。另外,除非它是一个非常小的循环,否则不要使用i。使用意味着什么的变量。

while read -rd' ' month; do
   some commands
   if [[ $buy -lt $sell ]]; then
      do this thing here
   fi
done

Bash不是半冒号终止,你不需要在一行结束时使用一个。在externam []上使用interan [[]]。不引用变量(例如&#34; $ buy&#34;)进行数值比较(例如-lt)。让你的时间保持在同一条线上 - 除了使其更具可读性之外,它没有其他目的。