I'm facing problem while running a script 'restart.sh'. Its main objective is to kill a process by id, and restart the process again.

The process name has 'DND' as below

$ ps -ef | grep DND
root   18425     1 60 11:53 pts/0    00:40:34 java -jar DND_Retry.xml

NOTE : The PID will be changed every time the script is executed.

1 part of script given below:

  echo "Killing BND Process"

pids=$(pgrep -f BND)
for pid in "${pids}"; do
  if [[ $pid != $$ ]]; then
    kill -2 "$pid"

sleep 2

while true
shut1=`more /Data/v3/nohup_bnd.out |  grep  "has been shutdown" | wc -l`
        if [ $shut1 -eq 1 ]; then

    echo "process ended now restart"

The problem is: The script executes successfully first time but, when I execute again, it doesn't kill the process. However if I kill the process manually with Kill -9, and again execute the script it executes successfully and produce the desired result.

Is there anything I need to modify in above script/condition. I need to perform Kill -2.

  • So, how are you starting the script and how do you restart it? Is there any difference in how it appears in the output of ps depending on how it was started? (I can't see where your script would restart the program). Also, you have BND in the script, and DND in the sample ps output and in the text. Is that relevant or just a typo?
    – ilkkachu
    Commented Feb 23, 2019 at 11:54
  • @ikkachu, It was a typo, it is BND..but the problem is, the script is not executing for the second time. Its not killing the PID 18425. Commented Feb 23, 2019 at 13:24

1 Answer 1


If you have multiple PIDs running, then quoted variable "${pids}" causes a problem. You need to remove the quotes.


$ pids=$(pgrep -f a_program_started_three_times)
$ for pid in "$pids"; do echo "pid is $pid"; done
pid is 563
$ for pid in $pids; do echo "pid is $pid"; done
pid is 563
pid is 564
pid is 565


I would add an extra check to the for-loop.

pids=$(pgrep -f BND)
# if pid(s) were found, then...
if [ $? -eq 0 ]; then
    # removed the quotes from "${pids}" here
    for pid in $pids; do
        if [[ $pid != $$ ]]; then
            kill -2 "$pid"

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .