在bash中,我想说"如果文件不包含XYZ,那么"做一堆事情.将其转换为代码的最自然方式是:
if [ ! grep --quiet XYZ "$MyFile" ] ; then
... do things ...
fi
Run Code Online (Sandbox Code Playgroud)
但是,当然,这不是有效的Bash语法.我可以使用反引号,但之后我将测试文件的输出.我能想到的两个选择是:
grep --quiet XYZ "$MyFile"
if [ $? -ne 0 ]; then
... do things ...
fi
Run Code Online (Sandbox Code Playgroud)
和
grep --quiet XYZ "$MyFile" ||
( ... do things ...
)
Run Code Online (Sandbox Code Playgroud)
我更喜欢第二个,它更像是Lispy和|| 控制流程在脚本语言中并不常见.我也可以看到第一个的参数,虽然当人们读到第一行时,他们不知道你为什么要执行grep,看起来你正在执行它的主要效果,而不仅仅是控制一个脚本分支.
是否有第三种更直接的方式使用一种if
陈述并具有grep
条件?
use*_*001 30
就在这里:
if grep --quiet .....
then
# If grep finds something
fi
Run Code Online (Sandbox Code Playgroud)
或者如果grep失败了
if ! grep --quiet .....
then
# If grep doesn't find something
fi
Run Code Online (Sandbox Code Playgroud)
您不需要[
]
(test
)来检查命令的返回值.试一试:
if ! grep --quiet XYZ "$MyFile" ; then
Run Code Online (Sandbox Code Playgroud)