我正在写一个bash脚本的问题。我想读取日志文件并对输出执行某些操作。但问题是它每次都记录两行而不是一行。所以每当我得到一个输出的副本而不是一行。
123.456.789
这是我在脚本中使用的输出:
#!/bin/bash
##############
logfile=/var/atlassian/application-data/jira/log/atlassian-ing-security.log
counter_a=0
counter_b=0
tail -fn0 /var/atlassian/application-data/jira/log/atlassian-jira- security.log | \
while read line ; do
echo "$line" | grep "FAILED"
if [ $? = 0 ]
then
echo "API action FAILED" >> $logfile
counter_a=$((counter_a+1))
echo "Total of $counter_a API actions FAILED" >> $logfile
else
echo "API action SUCCESFULL" >> $logfile
counter_b=$((counter_b+1))
echo "Total of $counter_b API actions SUCCESFULL" >> $logfile
fi
done
如何每次删除脚本中的第二行?
谢谢!
答案 0 :(得分:0)
问题是grep
的输出也会转到脚本的标准输出。你可以简单地让它沉默:
if echo "$line" | grep -q FAILED; then
echo "API action FAILED" >> $logfile
counter_a=$((counter_a+1))
echo "Total of $counter_a API actions FAILED" >> $logfile
else
echo "API action SUCCESFULL" >> $logfile
counter_b=$((counter_b+1))
echo "Total of $counter_b API actions SUCCESFULL" >> $logfile
fi
但是,更好的方法是避免在每一行上对grep
进行(相对)昂贵的调用,并使用shell本身来检测匹配。
tail ... | {
while read line ; do
if [[ $line = *FAILED* ]]; then
then
echo "API action FAILED"
counter_a=$((counter_a+1))
else
echo "API action SUCCESSFUL"
counter_b=$((counter_b+1))
fi
done
# You probably want to execute these just once, after the entire
# file has been processed.
echo "Total of $counter_b API actions SUCCESSFUL"
echo "Total of $counter_a API actions FAILED"
} >> "$logfile"