0

I'm using CentOS 7. I"m trying to capture the "master PID" of a process in a script variable. This is my script

#!/bin/sh

set -e

PID="$APP_ROOT/shared/pids/puma.pid"
echo "before ..."
MASTER_PID=`pgrep -f '^([^ ]*/)?puma '`
echo "after ..."
xxx

However, the word "after ..." is never printed out. There's something about this line

MASTER_PID=`pgrep -f '^([^ ]*/)?puma '`

which is causing things to behave badly, especially if there is no puma process running. Does anyone know a way to rewrite the above so that I can capture my master PID or at least allow execution to pass to the next line if it doesn't exist?

Dave
  • 2,548

2 Answers2

1

set -e Exit immediately if a command exits with a non-zero status.

Since pgrep fails when there is no matching PID, you are not able to execute echo "after" statement.

I think, removing set -e should solve your problem.

TheGeek
  • 156
1

If you want to keep the set -e, then you need to keep pgrep from failing, by:

MASTER_PID=`pgrep -f '^([^ ]*/)?puma ' || true`
Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
  • Consider telling him also that using $( .. ) instead of backticks might be better. – Vlastimil Burián May 15 '18 at 10:03
  • I think you just did! :) it was tangential to the core question, so I didn’t. There may be other improvements to what they’re doing, too. For command substitution differences, see: https://unix.stackexchange.com/q/5778/117549 – Jeff Schaller May 15 '18 at 10:20