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?

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
Dave
  • 2,348
  • 21
  • 54
  • 84

1 Answers1

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
Kusalananda
  • 320,670
  • 36
  • 633
  • 936
Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175