Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 具有多个参数的pgrep-f_Regex_Bash_Shell_Grep - Fatal编程技术网

Regex 具有多个参数的pgrep-f

Regex 具有多个参数的pgrep-f,regex,bash,shell,grep,Regex,Bash,Shell,Grep,我试图找到一个包含术语“someWord”和另外两个由$1和$2表示的术语的特定过程 7 regex="someWord.*$1.*$2" 8 echo "$regex" 9 [ `pgrep -f $regex` ] && return 1 || return 0 返回 ./test.sh foo bar someWord.*foo bar.* ./test.sh: line 9: [: too many arguments 我的正则表达式怎么了?直接在外

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

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

./test.sh foo bar
someWord.*foo bar.*
./test.sh: line 9: [: too many arguments
我的正则表达式怎么了?直接在外壳中进行pgrep很好。

好的,先生,也许是这样

[[ `pgrep -f "$regex"` ]] && return 1 || return 0
还是这个

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

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

pgrep -f "$regex" && return 1 || return 0.
如果
pgrep
成功,则返回1;否则,将返回0。但是,您所做的只是反转预期的退出代码。您可能想要做的只是将
pgrep
作为函数的最后一个语句;然后,
pgrep
的退出代码将成为您的函数的退出代码

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

如果您确实希望在命令返回错误时执行某些操作:

cmd="pgrep -f $regex"

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

这可能是真的,我会对它进行测试,但我的正则表达式没有被阻塞,因为它显示“someWord.*foo-bar.*”但应该是“someWord.*foo.*bar”?看起来
$1
设置为“foo-bar”,而
$2
根本没有设置。你能在问题中添加更多的
test.sh
吗?