Showing posts with label perl. Show all posts
Showing posts with label perl. Show all posts

14 March 2007

get environment variables of a process with ps - 2: the win!

Yeah, I got it!
First the solution, some comment right afterwards:
#!/usr/bin/perl -w

$catch = shift @ARGV;
while (<>) {
/(.*?) ([A-Z|_]*?=.* )+$catch=(\S*?) /;
print $1." ".$catch."=".$3."\n";
}
Things was more confusing with sed due to the fact that it pretends to work with the /pattern/substitution/ pair. Now I simply parse my line capturing what I'm interested in, and then using only it to make the output.
The interpretation is now straight forward:
  • take the first part of the string until the first group of capital letters or underscore followed by an equal sign; this will be the normal output for each process, and this will be printed out;
  • not be greedy looking for the equal sign, and take the firs you encounter (the ? after the *) so that this will match a single pair VAR=value; but then let this pairs be more than one (the + just after the second parentheses group);
  • then you will find a particular pair, which starts with the first argument i gave you ($catch)
Let's say that this perl script is named select.pl, you can pipe it after you ps call just my previous alias... but now it's parametric:
ps -ely --forest | grep myscript.pl | select.pl PWD
ps -ely --forest | grep myscript.pl | select.pl PATH
ps -ely --forest | grep myscript.pl | select.pl LOGIN
And if you now can't live without the --color feature of grep, perl can emulate it for you using the Term::ANSIColor module:
#!/usr/bin/perl -w

use Term::ANSIColor;

$catch = shift @ARGV;
while (<>) {
/(.*?) ([A-Z|_]*?=.* )+$catch=(\S*?) /;
print $1." ";
print color("red bold"), $catch, color("reset");
print "=".$3."\n";
}
Please enjoy!