3

I am checking via a bash script whether a process is running based on the PID stored in a file. I get the error shown above when the file does not exist as the command is trying to access the file and check whether the PID is really there, so it's normal, but I would like to avoid it if possible.

Is there such a way?

The command I am using can be found below.

if kill -0 $(cat "$pid_file")

Thank you in advance.

7
  • show the content of the pid_file - i bet you there is a \n at the end of that file. Commented Jun 22, 2015 at 13:35
  • In semi-human code: If $PID_file exists then kill kill -0 $(cat "$pid_file"). Also see if -e. Possible UNTESTED code: if [ -e $pid_file ] then echo "$pid_file found. Sending signal kill -0 $(cat "$pid_file") else echo "$pid_file does not exist." fi done Commented Jun 22, 2015 at 13:37
  • thanks for replying, the PID file just stores the PID process number of a running application...so when the application is not running and the file is not generated, I would like to test whether the PID exists anyway just to be on the safe side. Commented Jun 22, 2015 at 13:37
  • Try with cat "$pid_file" | head -n 1 | tr -d "\n" Commented Jun 22, 2015 at 13:38
  • Did you try with pgrep? check the -F switch. Commented Jun 22, 2015 at 13:40

3 Answers 3

3

[[ -f "$pid_file ]] && (cat "$pid_file" | head -n 1 | tr -d "\n")

This command will return a non-zero status. If you want an "always return zero" (sacrificing legibility):

[[ ! -f "$pid_file ]] || (cat "$pid_file" | head -n 1 | tr -d "\n")

1
  • Oh I see, so basically now I am doing the opposite, if the file exists or the PID exists based on the file...I will change it as your suggestion and come back, thanks. Commented Jun 22, 2015 at 14:29
2

You need a condition to check whether the file exists, and if you don't want to see any errors when you attempt to kill a PID that no longer exists, redirect its stderr to /dev/null. You'll end up with something like:

PID_EXISTS=$([[ -f "$pid_file" ]] && kill -0 $(<"$pid_file") 2> /dev/null && echo 1 || echo 0) 

This will store 1 for an existing pid, and 0 for a non-existing one. You may use the variable in a comparison, such as:

if [[ $PID_EXISTS -eq 1 ]]; then echo FOUND; else echo NOTFOUND; fi 

Or just print its result:

echo $PID_EXISTS 

No cat. Meow!

1
  • In this case I suggest to purge the not anymore existing PID from the list with a sed... Even if low there is a probability that this PID before or after will be used again... Commented Jun 22, 2015 at 14:21
1

Or, you can just use pgrep instead:

if pgrep -F "$pid_file" &>/dev/null; then echo yep else echo nope fi 

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.