【发布时间】:2019-09-23 21:51:56
【问题描述】:
我编写了一个脚本来检查最后 10 分钟的最后一个 httpd 错误日志,但我得到一个错误,它一直在循环:问题是脚本的输出是一个错误循环,直到日志文件结束 我通过运行 cmd date --date='-10min' 来获取日期 - 10 分钟,然后我逐行解析日志文件,然后检查日志文件中每一行的小时和分钟是否大于或等于日期的小时和分钟 -10 分钟 这是输出的一部分:
./test2.sh: line 26: [: -ge: unary operator expected
./test2.sh: line 26: [Mon: command not found
./test2.sh: line 26: [: -ge: unary operator expected
./test2.sh: line 26: [Mon: command not found
./test2.sh: line 26: [: -ge: unary operator expected
./test2.sh: line 26: [Mon: command not found
./test2.sh: line 26: [: -ge: unary operator expected
./test2.sh: line 26: [Mon: command not found
当我在这里尝试调试它时,这是问题的一部分,并且它在日志文件的每一行中重复:
+ IFS=
+ read -r line
+ errorBool=0
+ [[ [Sun Apr 28 03:52:39.791442 2019] [autoindex:error] [pid 15012]
[client 127.0.0.1:49054] AH01276: Cannot serve directory /var/www/html/:
No matching DirectoryIndex (index.html,index.php) found, and server-
generated directory index forbidden by Options directive == *:error* ]]
++ awk -F : '{printf $1}'
++ '[Sun' Apr 28 03:52:39.791442 '2019]' '[autoindex:error]' '[pid'
'15012]' '[client' '127.0.0.1:49054]' AH01276: Cannot serve directory
/var/www/html/: No matching DirectoryIndex '(index.html,index.php)' found,
and server-generated directory index forbidden by Options directive
test2.sh: line 26: [Sun: command not found
++ awk '{printf $4}'
+ '[' -ge 12 ']'
test2.sh: line 26: [: -ge: unary operator expected
代码如下:
#!/bin/bash
#SCRIPT TO CHECK THE ERROR LOGS IN THE LAST 10 MINS
#VARIABLES
#NUMBER OF ERROR LOGS
errorCount=0
DATE_10_MIN=$(date --date='-10min' | awk '{print $4}' )
DATE_10_MIN_HOURS=$(date --date='-10min' | awk '{print $4}' | awk -F :
'{print $1} ')
DATE_10_MIN_MIN=$(date --date='-10min' | awk '{print $4}' | awk -F :
'{print $2} ')
#_______________________#
while IFS= read -r line ; do
#BOOLEAN TO CHECK IF THE LINE HAVE THE EXPRESSION
errorBool=0
#if [[ $($line | awk '{print $4 }' | cut -c-8) -gt $DATE_10_MIN ]] ;
then
if [[ $line == *:error* ]] ; then
if [ [ $($line | awk '{print $4}' | awk -F : '{print $1}' )
-ge $DATE_10_MIN_HOURS ] && [ $($line | awk '{print $4}' | awk -F :
'{print $2}') -ge $DATE_10_MIN_MIN ] ]; then
errorBool=1
(( errorCount++ ))
echo $line
fi
fi
done < /var/log/httpd/error_log
echo "There were $errorCount error logs in the last 10 mins "
【问题讨论】:
-
欢迎来到本站! (1) 我看到你有
if [ [和] ]; then,括号之间有空格。如果删除空格,问题会消失吗? (2) 请edit your question 提供问题的详细信息?脚本是否因错误而终止,还是会产生意外结果? (3) 您是否还可以编辑问题以添加一个小的输入样本以及预期和实际输出?这将有助于我们进行测试。谢谢! -
我删除了空格并没有什么特别的,因为该脚本用于在最后 10 分钟内获取错误编号,该脚本的输出为:./test2.sh: line 26: [Mon:找不到命令 ./test2.sh:第 26 行:[:-ge:预期的一元运算符 ./test2.sh:第 26 行:[星期一:找不到命令 ./test2.sh:第 26 行:[:-ge:一元运算符预期 ./test2.sh:第 26 行:[星期一:找不到命令 ./test2.sh:第 26 行:[:-ge:预期一元运算符 ./test2.sh:第 26 行:[星期一:找不到命令它循环直到日志文件结束
标签: bash apache shell logging awk