输入不匹配时,防止grep返回错误 [英] Prevent grep returning an error when input doesn't match
问题描述
我想在bash脚本中写一段代码来检查程序是否已经运行。
我有以下内容来搜索bar是否正在运行
foo =`ps -ef | grep bar | grep -v grep`
grep -v grep
部分是为了确保grep在ps结果中不考虑bar
当bar未运行时,foo正确为空。但我的问题在于,脚本中有
set -e
如果某个命令返回错误,那么这是一个终止脚本的标志。
事实证明,当bar未运行时,grep -v grep与任何内容都不匹配,并且grep返回错误。我尝试使用-q或-s但无济于事。
有没有解决方法? Thx
当然:
ps -ef | grep bar | {grep -v grep ||真正; }
甚至:
ps -ef | grep bar | grep -v grep | cat
I want to write in a bash script a piece of code that checks if a program is already running. I have the following in order to search whether bar is running
foo=`ps -ef | grep bar | grep -v grep`
The
grep -v grep
part is to ensure that the "grep bar" is not taken into account in ps results
When bar isn't running, foo is correctly empty. But my problem lies in the fact tha the script has
set -e
which is a flag to terminate the script if some command returns an error. It turns out that when bar isn't running, "grep -v grep" doesn't match with anything and grep returns an error. I tried using -q or -s but to no avail.
Is there any solution to that? Thx
Sure:
ps -ef | grep bar | { grep -v grep || true; }
Or even:
ps -ef | grep bar | grep -v grep | cat
这篇关于输入不匹配时,防止grep返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!