Pgrep -f with multiple arguments

I am trying to find a specific process containing the term "someWord" and two other expressions represented by $ 1 and $ 2

7 regex="someWord.*$1.*$2" 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 regex? Running this pgrep directly in the shell works fine.

+8
bash regex shell grep
source share
3 answers

Good sir maybe it's

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

or

 [ "`pgrep -f '$regex'`" ] && return 1 || return 0 
+8
source share

First, there is no reason to wrap the pgrep command in anything. Just use its exit status:

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

If pgrep succeeds, you will return 1; otherwise, you return 0. However, all you do is change the expected exit codes. What you probably want to do is just let pgrep be the last statement of your function; then the pgrep exit code will be the exit code of your function.

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

If you really want to do something, if your command returns an error:

 cmd="pgrep -f $regex" if ! $cmd; then echo "cmd failed." else echo "ok." fi 
0
source share

All Articles