关于使用 shell 脚本检索 Laravel 日志报错信息变量中包含特殊字符的问题
- 问题描述
逐行检索一个文件中的内容在另一文件中是否存在,不存在则输出
- 环境复现
两个日志文件:
test.log、test_new.log
一个脚本文件:
check.sh
文件内容:
test.log文件中的内容:
local.ERROR: Use of undefined constant yui - assumed 'yui' {exception:[object] (ErrorException(code: 0): Use of undefined constant yui - assumed 'yui' at /data/wwwroot/test/laravel55/routes/web.php:15)
local.ERROR: Use of undefined constant yui - assumed 'yui' {exception:[object] (ErrorException(code: 0): Use of undefined constant yui - assumed 'yui' at /data/wwwroot/test/laravel55/routes/web.php:15)
test_new.log文件中的内容:
local.ERROR: Use of undefined constant yui - assumed 'yui' {exception:[object] (ErrorException(code: 0): Use of undefined constant yui - assumed 'yui' at /data/wwwroot/test/laravel55/routes/web.php:15)
local.ERROR: Use of undefined constant hhh - assumed 'hhh' {exception:[object] (ErrorException(code: 0): Use of undefined constant hhh - assumed 'hhh' at /data/wwwroot/test/laravel55/routes/web.php:15)
chech.sh文件中的内容:
#!/bin/bash
bak=$IFS
IFS=$'\n'
for i in $(cat test_new.log); do
if [ `grep '$i' test.log` ] ;then
continue
else
echo $i
break
fi
done
IFS=$bak
- 调试运行
预期:
输出 test_new.log 中第二行内容
实际:
输出 test_new.log 中第一行内容
- 问题猜想
检索时由于一行变量中存在特殊字符导致检索失败
- 验证猜想
- 结论
由于变量中包含特殊含义的字符 ( $, *, [, |, ^, (, ), / )等,导致检索失败
- 提出问题
请问各路大神,这种变量中存在特殊字符的检索问题改如何破解?或者有没有更好的办法能满足我的需求?
小弟学浅,望不吝赐教!
关于你提出的主要问题,用
--fixed-string
即可解决(grep
默认认为你要检索的是一个模式字符串)。另外其实不需要用
if [ ]
,直接||
更简单些。如果你选择用 if,那么可以去掉[ ]
,if 的本意即为检查程序的 Exit code。