tags:

views:

1400

answers:

5

Hi, assuming that I know the PID of a process and want to do a search in ps -A, how do I do it? I tried doing this:

echo "Enter PID to search: "
read PID
search=$(ps -A | grep -v PID | awk '{print $1}')

This returns me with a long list of PIDs. So how can I get use each individual value of the output and do:

if [ "$PID" = "*each_value_in_search_list*" ]; then
........

In this case i'm trying to compare what the user enters with the output of my command, so how do I do it? Am I doing the correct way in the first place? Or is there any other way to do this?

Thanks for your help, everyone who answered this question. (:

+3  A: 

You're grepping the output of ps for all lines which do not contain the literal string "PID". You want to use $PID instead to use the variable named PID instead of the literal "PID". Furthermore, since you do not want false positives on other fields matching the PID, just match on the first column:

search=$(ps -A | grep "^ *$PID\>" | awk '{print $1}')

The "\>" escape sequence matches the empty string at the end of a word.

Some versions of ps support a -p option to only give you the info about a specific PID, so you don't need grep or awk:

search=$(ps -p $PID)
Adam Rosenfield
POSIX ps supports the -p option - so odds are good that you're not going to find a ps on a reasonably up-to-date machine which doesn't support it. :)
dannysauer
+2  A: 

The -v switch for grep performs an inverted search, in other words you will get everything you DON'T want. After a variable is set, you should also reference it prefixed with $.

try this

#!/bin/bash

echo "Enter PID to search: "
read PID
search=$(ps --pid $PID -o comm=)

if [ $search ]
    then
        echo "Program: $search"
    else
        echo "No program found with PID: $PID"
fi
John T
+2  A: 

Your "grep -v PID" is a standard trick to remove the heading line, not a way to get the actual PID details from the output.

If all you want is the details for that process, just use:

search=$(ps -A | awk -v pid=$PID '$1==pid{print pid}')

That will set search to the PID in question if it exists or the empty string otherwise, which is what you appear to want.

There's a problem with doing a blind search for the PID (as opposed to checking column 1 with awk) is that you may pick up lines where that PID shows up in the command string.

paxdiablo
+2  A: 

If the root of the question is to check if the entered PID corresponds to a process entry (root). More specific, if you are able to send a signal to that process (user):

if kill -0 $PID >/dev/null 2>&1; then ...

It could be, of course, that this is not at all what you want. I felt free to "interpret" your question a bit ;)

TheBonsai
+3  A: 

Instead of using grep you could use the -p option to pass the PID directly to the ps command.

Dave Webb