mpersico has asked for the wisdom of the Perl Monks concerning the following question:

I have this line of code in a loop in shell:
pid=$(ps -l -p $pid | grep -v PPID | perl -ane 'print $F[4]')
The idea is to get the parent of the process. Other code is checking for other conditions. But that's not the problem. The problem is that $F[4] only works on some 'ps'. For the 'ps' in Cygwin, I need to use $F[1]. Sooooo, I naively tried this:
ppidi=4 [ $(uname) = 'Cygwin ] && ppidi=1 ... pid=$(ps -l -p $pid | grep -v PPID | \ perl -ane 'print $F[$ARGV[0]]' $ppidi);
which resulted in
Can't open 1: No such file or directory.
In short, once you use -n or -p, there is no way to use ARGV as arguments, and not have them sucked up as filenames to feed to the virtual while(<>) {} loop, is there?

Replies are listed 'Best First'.
Re: -n and -p suck up ARGV no matter what
by tybalt89 (Monsignor) on Oct 21, 2016 at 21:04 UTC

    This is perl, be very careful of saying "no matter what".

    echo -e "one\ntwo\nthree" | perl -ne 'INIT{$tmp = shift} print "$tmp - +> $_"' 42
      I knew someone would take that as a challenge. :-) Thank you.
Re: -n and -p suck up ARGV no matter what
by stevieb (Canon) on Oct 21, 2016 at 20:44 UTC

    With Perl, you can simply use getppid(), but since this isn't perl, you can use this:

    ps -o ppid= -p $pid

    ...and that should get you your parent PID without having to use Perl, sed etc.

Re: -n and -p suck up ARGV no matter what
by mpersico (Monk) on Oct 21, 2016 at 20:41 UTC
    Oh my goodness, I am so stupid. I should just parse the header looking for which column is PPID and use that.
    ps -l -p $$ | grep PPID | perl -ane '$i=0; while($i<@F && $F[$i] ne q(PPID)){$i++}; print $i if $i < @F'