Excluding grep from process list
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow
--
Chapters
00:00 Excluding Grep From Process List
00:34 Accepted Answer Score 30
01:13 Answer 2 Score 26
01:29 Answer 3 Score 16
01:40 Answer 4 Score 3
02:08 Answer 5 Score 3
02:58 Thank you
--
Full question
https://superuser.com/questions/409655/e...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#grep #ps #pid
#avk47
ACCEPTED ANSWER
Score 30
grep's -v
switch reverses the result, excluding it from the queue. So make it like:
ps aux | grep daemon_name | grep -v "grep daemon_name" | awk "{ print \$2 }"
Upd. You can also use -C
switch to specify command name like so:
ps -C daemon_name -o pid=
The latter -o
determines which columns of the information you want in the listing. pid
lists only the process id column. And the equal sign =
after pid
means there will be no column title for that one, so you get only the clear numbers - PID's.
Hope this helps.
ANSWER 2
Score 26
You can use a character class trick. "[d]" does not match "[d]" only "d".
ps aux | grep [d]aemon_name | awk "{ print \$2 }"
I prefer this to using | grep -v grep
.
ANSWER 3
Score 16
Avoid parsing ps
's output if there are more reliable alternatives.
pgrep daemon_name
pidof daemon_name
ANSWER 4
Score 3
The ps -C
option is not universal on all Unix based systems but if it works on your systems. Instead I would avoid grep altogether:
ps aux | awk '/daemon_name/ && !/awk/ { print $2 }'
No need to escape anything in single quotation marks. ps aux
will give you the full list of processes on most Unix based systems and awk
is typically installed by default.
ANSWER 5
Score 3
Use pgrep
to look for the pid of a process by name:
pgrep proc_name
With extra process name in the result (-l
):
pgrep -l proc_name
Look for and display the process name (-l
) and arguments (-f
):
pgrep -lf proc_name_or_argument
The good thing about pgrep
is that it will never report itself as a match. But you don't need to get the pid by pgrep
and then kill the corresponding process by kill
. Use pkill
instead:
pkill proc_name
Specify the SIGKILL
signal (-9
or -KILL
) instead of SIGTERM
(by default):
pkill -9 proc_name
Look for the process name (-l
) and arguments (-f
), ask for confirmation (-I
) before killing it by SIGKILL
signal (-9
or -KILL
):
pkill -KILL -Ilf proc_name_or_argument
Notice that the -I
option is only available on some versions of pkill
, e.g. the one on the OS X Mavericks.