I need to develop a shell script that would not be started if another instance of them self is running.
If I build a test.sh that monitors itself I need to know if it is already running and then abort, otherwise (if it not previously running) I can run
#!/bin/bash
loop() {
    while [ 1 ]; do
        echo "run";
        #-- (... omissis ...)
        sleep 30
      done
 }
 daemon="`/bin/basename $0`"
 pidlist=`/usr/bin/pgrep $daemon | grep -v $$`
 echo "1:[ $pidlist ]"
 pidlist=$(/usr/bin/pgrep $daemon | grep -v $$)
 echo "2:[ $pidlist ]"
 echo "3:[ `/usr/bin/pgrep $daemon | grep -v $$` ]"
 echo "4:["
 /usr/bin/pgrep $daemon | grep -v $$
 echo "]"
 if [ -z "$pidlist" ]; then
      loop &
 else
      echo "Process $daemon is already running with pid [ $pidlist ]"
 fi
 exit 0;
When I run the above script for the first time (no previous instances running) I get this output:
1:[ 20341 ]
2:[ 20344 ]
3:[ 20347 ]
4:[
]
I cannot understand why only 4th attempt does not return anything (as expected). What's wrong in my script? Do I have to redirect output of 4th command on a temporary file and then query that file in order to decide if I can run (or not) the loop function?
Thanks anyone would help me!
 
     
    