bash pgrep -f 带多个参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14837475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 04:32:09  来源:igfitidea点击:

pgrep -f with multiple arguments

regexbashshellgrep

提问by tommsen

i try to find a specific process containing the term "someWord" and two other terms represented by $1 and $2

我试图找到一个包含术语“someWord”和另外两个由 $1 和 $2 表示的术语的特定过程

 7   regex="someWord.*.*"
 8   echo "$regex"
 9   [ `pgrep -f $regex` ] && return 1 || return 0

which returns

返回

./test.sh foo bar
someWord.*foo bar.*
./test.sh: line 9: [: too many arguments

What happens to my regular expression? Doing that pgrep directly in the shell works fine.

我的正则表达式会发生什么?直接在 shell 中执行该 pgrep 工作正常。

回答by Steven Penny

Good sir, perhaps this

好先生,也许这个

[[ `pgrep -f "$regex"` ]] && return 1 || return 0

or this

或这个

[ "`pgrep -f '$regex'`" ] && return 1 || return 0

回答by chepner

First, there's no reason to wrap your pgrepcommand in anything. Just use its exit status:

首先,没有理由将您的pgrep命令包装在任何东西中。只需使用其退出状态:

pgrep -f "$regex" && return 1 || return 0.

If pgrepsucceeds, you'll return 1; otherwise, you'll return 0. However, all you're doing is reversing the expected exit codes. What you probably want to do is simply let the pgrepbe the last statement of your function; then the exit code of pgrepwill be the exit code of your function.

如果pgrep成功,您将返回 1;否则,您将返回 0。但是,您所做的只是反转预期的退出代码。您可能想要做的只是让 thepgrep成为您函数的最后一个语句;那么退出代码pgrep将是您的函数的退出代码。

something () {
   ...
   regex="someWord.*.*"
   echo "$regex"
   pgrep -f $regex
}

回答by Anew

If you really want to do something in case your command returns an error:

如果您真的想执行某些操作,以防您的命令返回错误:

cmd="pgrep -f $regex"

if ! $cmd; then
  echo "cmd failed."
else
  echo "ok."
fi