I'm writing a script that tries to kill a process. But the process might already been killed by others. How can I guard against it and prevent this kill command from terminating my process with throwing an error? I have PID of the process

  • How are you selecting the process you want to kill? – Joseph R. Jun 10 '14 at 17:55
  • @JosephR. I have it in a variable inside my bash function – Mohsen Jun 10 '14 at 17:56
  • I meant are you killing the process by name or by PID? – Joseph R. Jun 10 '14 at 17:56
  • 1
    If the PID does not exist because the process has already completed, the kill command will be completely harmless. Why do you even need to check this? – jw013 Jun 10 '14 at 18:22
  • 2
    @JosephR. The right solution to that (completely different problem) is something along the lines of kill pid || true. When all you have is a PID, it is impossible to avoid race conditions if the state of the PID changes between when you check it and when you try to do something with it. – jw013 Jun 10 '14 at 18:26

Look into using pkill instead of kill. It will return 1 if no process matched. Test exit status of pkill to determine if it actually killed anything

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.