parasit
parasit

Reputation: 506

Strange grep behaviour in scripts

In one of my tools is needed the PID of specyfic process in system. I try do this by following command:

parasit@host:~/# ps -ef | grep beam.smp |grep -v grep |awk '{ print $2 }' |head -n1
11982

Works fine, but when i try use the same command in script in the vast majority of cases got PID of grep instead of target process (beam.smp in this case) despite of 'grep -v grep`.

parasit@host:~/# cat getPid.sh
#!/bin/bash

PROC=$1    
#GET PID
CMD="ps -ef | grep $PROC |grep -v grep |awk '{ print \$2 }' |head -n1"
P=`eval $CMD`


parasit@host:~/# bash -x ./getPid.sh beam.smp 
+ PROC=beam.smp
+ CMD='ps -ef |grep beam.smp |grep -v grep |awk '\''{ print $2 }'\'' |head -n1'
++ eval ps -ef '|grep' beam.smp '|grep' -v grep '|awk' ''\''{' print '$2' '}'\''' '|head' -n1
+++ head -n1
+++ awk '{ print $2 }'
+++ grep -v grep
+++ grep beam.smp
+++ ps -ef
+ P=2189

Interestingly, it is not deterministic, I know it sounds strange, but sometimes it works OK, and sometimes no, I have no idea what it depends on.

How it is possibile? Is there any better method to get rid of "grep" from results?

BR Parasit

Upvotes: 0

Views: 118

Answers (1)

Bach Lien
Bach Lien

Reputation: 1060

pidof -s is made for that (-s: single ID is returned):

pidof -s "beam.smp"

However, pidof also returns defunct (zombie, dead) processes. So here's a way to get PID of the first alive-and-running process of a specified command:

# function in bash

function _get_first_pid() {
  ps -o pid=,comm= -C "$1" | \
     sed -n '/'"$1"' *$/{s:^ *\([0-9]*\).*$:\1:;p;q}'
}

# example

_get_first_pid "beam.smp"

  1. -o pid=,comm=: list only PID and COMMAND columns; ie. only list what we need to check; if all are listed then it is more difficult to process later on
  2. -C "$1": of the command specified in -C; ie. only find the process of that specific command, not everything
  3. sed: print only PID for first line that do not have "defunct" or anything after the base command name

Upvotes: 1

Related Questions