Excluding grep from process list

I have cobbled together a command to return the process ID of a running daemon:

ps aux | grep daemon_name | awk "{ print \$2 }"

It works perfectly and returns the PID, but it also returns a second PID which is presumably the process I'm running now. Is there a way I can exclude my command from the list of returned PIDs?

I've tested it a few times and it appears my command is always the second PID in the list, but I don't want to grab just the first PID in case it's inaccurate.


Solution 1:

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.

Solution 2:

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.