为什么“如果 $(ps aux | grep ...)"在 Bash 中总是成功?

问题描述:

为什么下面的 if 语句会成功?

Why the following if statement succeeds ?

if $(ps aux | grep -q "bla bla") ; then echo "found" ; fi

因为 grep 进程本身是由 ps 返回的.您可以欺骗" grep 通过包围字符类 [ ] 中的搜索字符之一来不匹配自身,这不会改变功能:就这样做:

Because the grep process itself is being returned by ps. You can "trick" grep to not match itself by surrounding one of the search characters in a character class [ ] which doesn't change the functionality: Just do:

if ps aux | grep -q "[b]la bla" ; then echo "found" ; fi

此外,不需要使用进程替换$().if 将对管道链中最后一个命令的成功起作用,这正是您想要的.

Also, the use of process substitution $() is unnecessary. The if will work on the success of the last command in the pipe chain, which is what you want.

注意:字符类技巧起作用的原因是因为 ps 输出仍然有字符类括号,但是当 grep 正在处理搜索字符串,它使用括号作为语法而不是一个固定的字符串来匹配.

Note: The reason the character class trick works is because the ps output still has the character class brackets but when grep is processing the search string, it uses the brackets as syntax rather than a fixed string to match.