当输入不匹配时防止grep返回错误 [英] Prevent grep returning an error when input doesn't match

查看:17
本文介绍了当输入不匹配时防止grep返回错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 bash 脚本中编写一段代码来检查程序是否已经在运行.我有以下内容来搜索 bar 是否正在运行

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`

 grep -v grep

部分是为了确保在 ps 结果中不考虑grep bar"

part is to ensure that the "grep bar" is not taken into account in ps results

当 bar 未运行时, foo 正确为空.但我的问题在于脚本具有

When bar isn't running, foo is correctly empty. But my problem lies in the fact tha the script has

 set -e

如果某些命令返回错误,这是一个终止脚本的标志.事实证明,当 bar 未运行时,grep -v grep"与任何内容都不匹配,并且 grep 返回错误.我尝试使用 -q 或 -s 但无济于事.

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

推荐答案

当然:

ps -ef | grep bar | { grep -v grep || true; }

甚至:

ps -ef | grep bar | grep -v grep | cat

这篇关于当输入不匹配时防止grep返回错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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