home user wrote:
After coming to think that login and interactive modes are not the
answer, I
started digging into ps, and piping its output into grep. Unfortunately,
that generates another process "grep ksysguard ...". Piping into "grep
-v
..." also doesn't help. After groping all over grep and bash today and
trying lots of things, I got lucky. In the GNU Grep 3.3 web page
"http://www.gnu.org/software/grep/manual/grep.html",
I found this:
-----
7. Why do people use strange regular expressions on |ps| output?
ps -ef | grep '[c]ron'
You could also use 'pgrep ksysguard' instead of piping ps to
grep. That avoids both a pipe and the need to hide the grep
command from the grep.
The main problem is solved. But this leaves me with two follow-up
questions:
1. How does the [first_letter] prevent matching the ps output line for
grep? (I'm almost certain I'm not the only member of this list not knowing
the answer to this!) It works, and I'm using it, but it would be good to
really understand how it works (beyond what the GNU grep page says). I saw
no hint of an answer in the regular expression write-up.
When you run ps -ef | grep ksysguard, the ps list includes
entries for both ps -ef and grep ksysguard. Adding the
bracets around a character in the grep command means that
the grep pattern is looking for that one character followed
by the others, in the case of 'grep [k]sysguard' the regular
expression is k followed by sysguard.
In the ps -ef output, the string [k]sysguard doesn't match
because there are literal brackets there. In the grep
regex, those brackets have special meaning. So this is a
good method for filtering such matches in the output of ps.
But pgrep is generally easier and purpose-built for that
particular problem.
2. Is there a way to have a *single* grep match one string and not
another.
Example: find all lines containing "ksysguard" but not "grep". Note
that
grep ksysguard | grep -v grep
is *not* what I'm looking for.
Yes, by ensuring the regex is precise and doesn't match both
lines, which is just what using [k]sysguard does. You might
be able to do this with something fancy like a negative
lookbehind, using 'grep -P' but I'm not sure.
Or you could use a regex which took advantage of the ps -ef
output format, like ps -ef | grep '[0-9] ksysguard'. That
won't match the grep for ksysguard because it's only looking
for a number followed by a space, followed by ksysguard.
Both are far less elegant/readable than grep [k]sysguard. :)
Which is itself less elegant than using pgrep. And in this
case, I think, pgrep is far less elegant than using the
desktop's autostart functions, as Ed showed for both Gnome
and KDE.
--
Todd