Reputation: 237
i try to find a specific process containing the term "someWord" and two other terms 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 regular expression? Doing that pgrep directly in the shell works fine.
Upvotes: 16
Views: 18236
Reputation: 1
Good sir, perhaps this
[[ `pgrep -f "$regex"` ]] && return 1 || return 0
or this
[ "`pgrep -f '$regex'`" ] && return 1 || return 0
Upvotes: 10
Reputation: 5492
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
Upvotes: 0
Reputation: 531055
First, there's no reason to wrap your pgrep
command in anything. Just use its exit status:
pgrep -f "$regex" && return 1 || return 0.
If pgrep
succeeds, 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 pgrep
be the last statement of your function; then the exit code of pgrep
will be the exit code of your function.
something () {
...
regex="someWord.*$1.*$2"
echo "$regex"
pgrep -f $regex
}
Upvotes: 2