Multiple instances of bash script on logout and login

I made a simple script that runs in an endless loop. It looks like this:

while :
do
   #operations
   sleep 5
done

      

and I added it to startup programs like this .

Everything works fine, but after logging out, I have 2 instances of this process script (3 after next logout, etc.). Only one of them shows notifications, but both of them start their own processes sleep

.

What can I do to fix this problem?

+3


source to share


1 answer


Logging out does not kill all processes. You need to kill this process yourself. One way is to add a conditional kill

to your script.

Example:

#!/bin/bash
for proc in $(pgrep $(basename "$0"));do
[[ $proc -ne $$ ]] && kill $proc
done
while :
do
   #operations
  sleep 5
done

      

If you run this script twice, the second one will kill the previous / s and make sure that only one instance of this script is executed at a time.

If there are multiple users using this process, you may want it to be user specific. To do this, change the line:



[[ $proc -ne $$ ]] && kill $proc

      

in

[[ $(echo $(pgrep -u $USER) | grep -o $proc) -ne $$ ]] && kill $proc

      

Note. Sometimes your process can get into a state where there is no normal command kill

to kill them. Use kill -9

in these cases.

+4


source







All Articles