为什么此代码可以正常工作,而相同条件的其他版本却不能?
if grep -q string file; then
echo found
else
echo not found
fi
Run Code Online (Sandbox Code Playgroud)
这不起作用:
if [ ! `grep -q string file` ]; then
echo not found
else
echo found
fi
Run Code Online (Sandbox Code Playgroud)
`grep -q string file`
在反引号(或内部$(...)
,这是优选的),将被替换输出的grep
。由于-q
已使用,这将是一个空字符串。
要否定测试,只需!
在它之前插入:
if ! grep -q pattern file; then
echo not found
else
echo found
fi
Run Code Online (Sandbox Code Playgroud)
如果你真的想搜索一个字符串(而不是一个正则表达式),那么你也应该使用-F
with grep
。