Warm tip: This article is reproduced from stackoverflow.com, please click
bash process scripting

Change the name of a script in memory OR other work around

发布于 2020-04-13 10:31:00

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
Questioner
El_Manuel0
Viewed
67
franzisk 2020-02-03 23:14

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