Reputation: 782
So, i've got a script, that firsts search for itself with awk and ps, and kills every instance if it finds something, or else, execute something if it doesnt. The problem is that it always find an instance of itself, as the action of running the scripts creates a process, therefore it never really executes something else and enters in a loop of killing itself.
The question is: Is there a way i can change the name of the process running? or is there any other workaround that fixes this eternal loop?
The script
#!/bin/bash
asd=$(ps aux | grep -v "color=auto" | grep "S\|R\|S+" | grep "bash asd.sh" | awk '{print $2}')
echo $asd
if [ -z "$asd" ]
then
while true
do
a=$(docker ps -a | awk '/137/ {print $1}')
## si container "a" esta parado por error 137, reiniciar
if [ ! -z "$a" ]
then
docker restart $a
echo "se reinicio el container $a, fallo por falta de memoria (error 137)"
fi
sleep 500
done &
else
echo " #### Matando Script #### "
sudo kill $asd
fi
Upvotes: 0
Views: 92
Reputation: 1963
Don't check if the process is running, check how many of your processes are running. If more than one, it means it is running, since one belongs to $0 (actual script).
Here is my solution, I added wc -l (counting output lines) in your ps command
#!/bin/bash
asd=$(ps aux | grep -v "color=auto" | grep "S\|R\|S+" | grep "bash asd.sh" | awk '{print $2}' | wc -l)
echo $asd
if [ "$asd" -gt "1" ]
then
while true
do
a=$(docker ps -a | awk '/137/ {print $1}')
## si container "a" esta parado por error 137, reiniciar
if [ ! -z "$a" ]
then
docker restart $a
echo "se reinicio el container $a, fallo por falta de memoria (error 137)"
fi
sleep 500
done &
else
echo " #### Matando Script #### "
sudo kill $asd
fi
Upvotes: 1