0

I have a shell script that looks like this " pgrep 'process' | xargs kill -9 " but if the 'process' does not exist, the kill command will complain that there is no input. my question is: is there a way to exit from the code cleanly if there is no process to kill? something like 'if pgrep return 0' run something else. some kind of try, except in bash script.

1 Answers1

2

If you are using Gnu xargs, you can use the -r flag to avoid executing kill if there are no processes. However, the simplest solution is to use pgrep's cousin, pkill, which was designed for this very purpose.

rici
  • 234,347
  • 28
  • 237
  • 341