Igor
Igor

Reputation: 1424

Bash script iterate over PID's and kill items

I try to kill all occurrences of a process, what's happen actually an iteration stops after first item, what's wrong here ?

#!/usr/bin/env bash

SUPERVISORCLS=($(pidof supervisorctl))

for i in "${SUPERVISORCLS[@]}"
    do
        echo $i
        exec sudo kill -9 ${i}
    done

Before I tried sth like this as solution for restart script, but as well script was not always executed at total always only one if block was executed.?

ERROR0=$(sudo supervisord -c /etc/supervisor/supervisord.conf  2>&1)

if [ "$ERROR0" ];then
    exec sudo pkill supervisord
    exec sudo supervisord -c /etc/supervisor/supervisord.conf
    echo restarted supervisord
fi

ERROR1=$(sudo supervisord -c /etc/supervisor/supervisord.conf  2>&1)

if [ "$ERROR1" ];then
     exec sudo pkill -9 supervisorctl
     exec sudo supervisorctl -c /etc/supervisor/supervisord.conf
     echo restarted supervisorctl
fi

Upvotes: 0

Views: 1366

Answers (1)

Eric Renouf
Eric Renouf

Reputation: 14500

exec replaces your process with the executable that's the argument to it, so you will never execute another statement in your script after it hits an exec. Your process will no longer exist. In the first example your process will no longer be your script it will be kill and pkill in the second.

To fix it, just remove exec from all those lines. It's not needed. When executing a script the shell will execute the commands on every line already, you don't have to tell it to do so.

Upvotes: 2

Related Questions