grep在bash脚本中的行为与交互式shell中的行为不同

tom*_*afe 2 bash shell grep

在我的bash脚本中,我试图解析状态文件并根据某些关键字检测错误.我将这些前缀存储在列表中,然后循环遍历它们.

Bash脚本:

status_page="/path/to/file.txt"
list="aaa bbb ccc ddd"

for pre in $list
do
    echo "grep '\w\w\w${pre}-.*\.lin failed' ${status_page}" # debug
    if grep '\w\w\w${pre}-.*\.lin failed' ${status_page}; then
        echo "Found error!"
        exit 8;
    fi
done
Run Code Online (Sandbox Code Playgroud)

/path/to/file.txt:

xyzfff-tool.lin failed
xyzggg-exec.lin failed
rstccc-tool.lin failed
Run Code Online (Sandbox Code Playgroud)

bash脚本应该捕获该行rstccc-tool.lin failed,但它会跳过它.

为了调试,我逐字打印grep命令,当我复制该行并在我的shell(tcsh)中发出命令时,它返回该行...

贝壳:

$ grep '\w\w\wccc-.*\.lin failed' /path/to/file.txt
    rstccc-tool.lin failed
$ echo $?
0
Run Code Online (Sandbox Code Playgroud)

如果grep可以在我正常发出命令时找到该行,那么当bash脚本调用grep时它怎么会找不到呢?

use*_*001 6

该变量不会用单引号扩展.试试双引号:

if grep "\w\w\w${pre}-.*\.lin failed" "${status_page}"; then
Run Code Online (Sandbox Code Playgroud)