2

I’m using Amazon Linux. I want to start a process provided one isn’t running already. This is a bash script I embed within a Jenkins Maven job. So I have

pids=$(pidof /usr/bin/Xvfb)
if [ ! -n "$pids" ]; then
    Xvfb :0 -screen 5 1024x768x8 &
fi

Unfortunately, if there is no process, the line “pids=$(pidof /usr/bin/Xvfb)” returns a failing exit code and none of the other lines following are executed. Is there a way I can write the above such that no failed exit codes will be returned?

4
  • 1
    Just use if ! pidof /usr/bin/Xvfb; then : do something; fi
    – cuonglm
    Apr 28, 2016 at 1:51
  • I tried "if ! pidof /usr/bin/Xvfb; then : Xvfb :0 -screen 5 1024x768x8 &; fi" and got the error, "syntax error near unexpected token `;'".
    – Dave
    Apr 28, 2016 at 2:24
  • Should be if ! pidof /usr/bin/Xvfb; then Xvfb :0 -screen 5 1024x768x8 & fi" if you want to run command in background.
    – cuonglm
    Apr 28, 2016 at 2:28
  • if ! pgrep Xvfb; then ... should do the trick.
    – DopeGhoti
    Apr 28, 2016 at 2:44

1 Answer 1

1

If you're running under set -e, add || true after a command to ignore a failure of that command.

pids=$(pidof /usr/bin/Xvfb || true)
if [ ! -n "$pids" ]; then
    Xvfb :0 -screen 5 1024x768x8 &
fi

But since pidof returns a nonzero status if no processes are found, you could directly test its return status instead of checking whether its output is empty.

if ! pidof /usr/bin/Xvfb >/dev/null 2>&1; then
    Xvfb :0 -screen 5 1024x768x8 &
fi

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .