How to get linux process id alone using perl

perl

Solution

perl's backticks and qx// interpolate variables, so when you write:

my $process_chk_command = `ps -ef | grep truecontrol | awk '{print $2}'`;

perl interpolates the special variable `$2`. In your case, `$2` is not set, and thus expands to the empty string, so the awk command is simply `{print}`.

You could escape the dollar sign (``ps ... | awk '{print \$2}'``) to avoid this.

(As an aside, I'd recommend `grep [t]ruecontrol` to prevent grep from matching its own process table entry, or that of its parent shell which constructs the pipeline. sh aficionados with a POSIX bent might additionally suggest ``ps -eo pid,comm,args | awk '/[t]ruecontrol/{print \$1}'``.)

Problem

When i execute the below command in command prompt it works fine. but when i include the same in perl script, it shows the whole process name. ``` ps -ef | grep truecontrol | awk '{print$2}' ``` returns ``` 4567 3456 ``` When I execute it throught perl, it shows the whole process details. I want to assign it to a variable array and work on it. Let me know how to do it? ``` my $process_chk_command = `ps -ef | grep truecontrol | awk '{print$2}'`; print($process_chk_command); root 9902 9890 0 05:50 ? 00:00:03 /opt/abc/jre/bin/java -DTCFTP=1 -d64 -Xms16m -Xmx64m -Djava.library.path=/opt/abc/server/ext/wrapper/lib -cla ```

Original source