1

I have the following bash code which checks that a process is running:

is_running() {
 ps `cat "$pid_file"` > /dev/null 2>&1
}

The problem is that is_running is always evaluated to true.

$pid_file contains a process ID that isn't listed when I run ps. I would like in this case, is_running to return false.

How can I modify it for that purpose?

heemayl
  • 39,294
  • 7
  • 70
  • 76
bsky
  • 19,326
  • 49
  • 155
  • 270

1 Answers1

3

You are missing the -p option:

ps -p PID

In bash, i would simply do:

is_running() { ps -p $(<"$1") &>/dev/null ;}

and will give the filename as an argument to the function:

is_running /pid/file

  • You need to start using the newer command substitution syntax $() instead of the arcane `...`

  • bash supports a shorthand (&>) for indicating the redirection of STDOUT and STDERR

mklement0
  • 382,024
  • 64
  • 607
  • 775
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • ++; as an aside: while using `-p` is definitely the right thing to do, because it is the POSIX-compliant way to pass a PID, in all `ps` implementation I've come across something like `ps $$` works too. – mklement0 Jan 25 '17 at 15:41