The problem here, as @Florian perceptively figured out, is that the shell is expanding the glob characters in your search string to a matching filename before passing the string on to grep
.
Running ps aux | grep foo
is problematic since the grep foo
command itself will match foo
and so appear in the output. There are two common, if convoluted, workarounds for this. You either add a grep -v grep
at the end of the pipe, or you use grep [f]oo
instead. Since grep
works with regular expressions, it will treat [f]
as "any character in the list of characters inside the brackets". Since the only character in the brackets is f
, [f]oo
is equivalent to foo
. However, the grep
process showing up in the ps
results will have the string [f]oo
and is, therefore, not found by grep
.
This becomes more complicated if, as seems to be the case for you, you have a file called foo
in your current directory. Because you haven't quoted the expression you gave to grep
(because you used [s]elenium
and not '[s]elenium'
or "[s]elenium"
), the shell will treat it as a glob and expand it to the matching file name. This renders the [s]elenium
trick useless since what is actually passed to grep
is selenium
and not [s]elenium
so the grep will match itself.
All this, however, only happens because you're not using the right tool for the job. As is so often the case, there's an app for that!
Don't use grep
+ ps
. Instead, use pgrep
which is designed to do precisely what you want:
NAME
pgrep, pkill - look up or signal processes based on name and other
attributes
SYNOPSIS
pgrep [options] pattern
pkill [options] pattern
DESCRIPTION
pgrep looks through the currently running processes and lists the
process IDs which match the selection criteria to stdout. All the cri‐
teria have to match. For example,
$ pgrep -u root sshd
So, in your case, you can just do
pgrep selenium
Or, since you're running it via java
, use -f
which searches through the entire command line:
pgrep -f selenium
java
command. My approach would be just to matchselenium
string and pipe intogrep -v grep
to remove grep command itself – Sergiy Kolodyazhnyy Jun 15 '16 at 15:30