John
John

Reputation: 23

Parsing grep output

I'm trying to make a server manager and here is what I have so far:

<?php
$COMMAND = shell_exec('ps ax --format command | grep skulltag');
$arr = explode("./",$COMMAND);
$text = shell_exec('pgrep -u doom');
$arrtext = preg_split('/\s+/', $text);
 for( $i = 1; $i < count($arr); $i++ ) {
    echo $i,". PROCESS ID ",$arrtext[$i]," Command issued: ",$arr[$i];
    echo '<br>';
 }
?>

As you can see, I'm separating the $COMMAND string with ./ (file execution). However, for some reason at the end of the list there's this:

sh -c ps ax --format command | grep skulltag grep skulltag 

Here is the full output for reference:

  1. PROCESS ID 4793 Command issued: skulltag-server
  2. PROCESS ID 4956 Command issued: skulltag-server -port 13000
  3. PROCESS ID 4958 Command issued: skulltag-server -port 13001 sh -c ps ax --format command | grep skulltag grep skulltag

What would be the easiest and most effective way to get rid of that line, and how would I do it? Thanks.

Upvotes: 1

Views: 2162

Answers (2)

webb
webb

Reputation: 4340

Change this:

ps ax --format command | grep skulltag

To this:

ps ax --format command | grep [s]kulltag

That way, the grep command itself contains the string '[s]kultag', which is not matched by the grep regular expression '[s]kultag'.

Also, two suggestions: 1. there's no guarantee that your initial ps | grep and your later pgrep will line up. Instead, use a single pgrep:

pgrep -afl skulltag

And 2. your for loop starts with 1, which will skip the process in arr[0].

Your php could be rewritten something like this:

$processes = explode("\n", shell_exec('pgrep -afl skulltag'));
foreach($processes as $i => $process) {
    ($pid, $command) = explode(' ',$process,2);
    echo $i+1,". PROCESS ID ",$pid," Command issued: ",$command;
    echo '<br>';
}

Upvotes: 2

mouviciel
mouviciel

Reputation: 67879

My quick and dirty solution is to append | grep -v grep to the command.

Upvotes: 1

Related Questions