为什么"如果$(的ps aux | grep的...)QUOT;总是击成功? [英] Why "if $(ps aux | grep ...)" always succeeds in Bash?

查看:91
本文介绍了为什么"如果$(的ps aux | grep的...)QUOT;总是击成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下如果语句成功?

 如果$(的ps aux | grep的-q喇嘛喇嘛);然后回声发现;科幻


解决方案

由于该的grep 过程本身是由返回 PS 。你可以在绝招的grep 不被周围的搜索字符中的一个字符类匹配本身 [] 这不改变的功能:
只要做到:

 如果的ps aux | grep的-q[B]拉喇嘛;然后回声发现;科幻

另外,使用过程中替换 $()的是不必要的。在如果将在最后一个命令在管道链,成功的工作,这是你想要的。

注意的:字符类招工作的原因是因为 PS 输出仍然具有字符类括号,但是当的grep 正在处理搜索字符串,它使用了括号作为语法,而不是一个固定的字符串相匹配。

Why the following if statement succeeds ?

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

解决方案

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

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.

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.

这篇关于为什么"如果$(的ps aux | grep的...)QUOT;总是击成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆