解决方案:我的日期变量格式错误(日期和星期几被翻转)。我更改了这个,然后使用@PesaThe下面提出的if
语句而不是我的测试。
原帖:
我正在编写一个bash脚本,作为服务器日常维护任务的一部分运行。这个特殊的工作是搜索input_file中匹配昨天和今天的时间戳的条目。这是我的日期变量。
today=$(date "+%a, %b %d %Y")
yesterday=$(date --date=yesterday "+%a, %b %d %Y")
以下是声明,它们应该是:
declare -- adminLogLoc="/opt/sc/admin/logs/"
declare -- adminLog="/opt/sc/admin/logs/201801.log"
declare -- today="Tue, Jan 02 2018"
declare -- yesterday="Mon, Jan 01 2018"
declare -- report="/maintenance/daily/2018-01-02_2.2.txt"
以下是我需要输出的一些实际日志条目。这些是grep $today $adminLog | grep error
Tue, 02 Jan 2018 14:38:50 +0000||error|WARNING|13|Query #2464 used to generate source data is inactive.
Tue, 02 Jan 2018 14:38:50 +0000||error|WARNING|13|Query #2468 used to generate source data is inactive.
Tue, 02 Jan 2018 14:38:50 +0000||error|WARNING|13|Query #2470 used to generate source data is inactive.
Tue, 02 Jan 2018 14:38:50 +0000||error|WARNING|13|Query #2474 used to generate source data is inactive.
以下是我试图运行的if语句:
# Check for errors yesterday
if [ $(grep $yesterday $adminLog|grep "error") != "" ]; then
echo "No errors were found for $yesterday." >> $report
else
$(grep $yesterday $adminLog|grep "error") >> $report
fi
# Check for errors today (at the time the report is made, there
# probably won't be many, if any at all)
if [ $(grep $today $adminLog|grep "error") != "" ]; then
echo "No errors were found for $today." >> $report
else
$(grep $today $adminLog|grep "error") >> $report
fi
我尝试了几种方法,例如在测试中的变量周围放置双引号,等等。当我在设置变量后在命令行中运行grep搜索时,它工作正常,但是当我在测试括号中运行它时,grep使用每个术语(即Tue,Jan ......等)作为单独的参数。我也试过
grep $yesterday $adminLog 2> /dev/null | grep -q error
if [ $? = "0" ] ; then
没有运气。
如何让这个测试工作,以便我可以将指定的条目输入我的日志文件?谢谢。
答案 0 :(得分:0)
请你试试下面的脚本,如果这有助于你,请告诉我。这段代码将有助于简单地打印昨天和今天的日志,以防你想将它们输入到输出文件中,我们也可以相应调整它。
#!/bin/bash
today=$(date "+%a, %b %d %Y")
yesterday=$(date --date=yesterday "+%a, %b %d %Y")
todays=$(grep "$today" Input_file)
yesterdays=$(grep "$yesterday" Input_file)
if [[ -n $todays ]]
then
echo "$todays"
else
echo "no logs found for todays date."
fi
if [[ -n $yesterdays ]]
then
echo "$yesterdays"
else
echo "NO logs found for yesterday's date."
fi