top | item 14270264

(no title)

gwu78 | 8 years ago

Example line from the Openshift reload-haproxy script:

  old_pids=$(ps -A -opid,args | grep haproxy | egrep -v -e 'grep|reload-haproxy' | awk '{print $1}' | tr '\n' ' ')
Can we do this without grep, egrep and awk? Would this work?

  old_pids=$(exec ps -A -opid,args |sed -n '/sed/d;/reload-haproxy/d;/haproxy/{s/ .*//;p};'|tr '\n' ' ')

discuss

order

tyingq|8 years ago

Haproxy supports a directive called pidfile that causes it to write it's pid to that file at startup.

If you still want grep, without it matching itself, an old trick is egrep '[h]aproxy' or similar.

Egrep, as opposed to pgrep, is more widely installed on non Linux systems like osx.

ploxiln|8 years ago

Yeah, the "ps | grep | grep -v grep" pattern is silly, there are a few better ways. In this case just:

    old_pids=$(pgrep '^haproxy')

gwu78|8 years ago

"... is silly, there are better ways."

I see this usage often where it seems like

  grep pattern1 | grep -v pattern2 
can be replaced by

  sed -n '/pattern1/d;/pattern2/p'
or at least

  sed '/pattern1/!d' | sed '/pattern2/d'
or

  sed -n 's/pattern1pattern2//g;/pattern2/p'
But I must be missing something obvious.

For example look at the "grep -v" usage here:

https://github.com/thomwiggers/qhasm/raw/master/qhasm-arm

Is there something wrong with using

   sed '/^op:livefloat80:/d'
Moreover, in the last line, why not use

  sed 's/\$/#/g'
instead of

  tr '$' '#'
Apologies if I am missing the obvious.

gnaritas|8 years ago

It's not silly at all, it's simple; there's many ways to accomplish something and knowing a shorter more precise way to do something doesn't make the longer simple ways silly. The author didn't know about pgrep, so he used what he did know about, ps and grep, nothing remotely silly about that; it's pragmatic.

vbernat|8 years ago

"args" could be replaced by "comm" to not filter grep. grep could be replaced by awk:

    ps -A -opid,comm | awk '($2 == "haproxy") {printf "%d ",$1}'
However, "pidof haproxy" would work too.