Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Continue script if only one instance is running? [duplicate]

now this is embarrassing. I'm writing quick script and I can't figure out why this statement don't work.

if [ $(pidof -x test.sh | wc -w) -eq 1 ]; then echo Passed; fi

I also tried using back-ticks instead of $() but it still wouldn't work.

Can you see what is wrong with it? pidof -x test.sh | wc -w returns 1 if I run it inside of script, so I don't see any reason why basically if [ 1 -eq 1 ] wouldn't pass.

Thanks a lot!

like image 256
Gargauth Avatar asked Mar 27 '10 17:03

Gargauth


3 Answers

Jefromi is correct; here is the logic I think you want:

#!/bin/bash
# this is "test.sh"

if [ $(pidof -x test.sh| wc -w) -gt 2 ]; then 
    echo "More than 1"
    exit
fi

echo "Only one; doing whatever..."
like image 136
Kevin Little Avatar answered Sep 28 '22 09:09

Kevin Little


Ah, the real answer: when you use a pipeline, you force the creation of a subshell. This will always cause you to get an increased number:

#!/bin/bash

echo "subshell:"
np=$(pidof -x foo.bash | wc -w)
echo "$np processes"   # two processes

echo "no subshell:"
np=$(pidof -x foo.bash)
np=$(echo $np | wc -w)
echo "$np processes"   # one process

I'm honestly not sure what the shortest way is to do what you really want to. You could avoid it all by creating a lockfile - otherwise you probably have to trace back via ppid to all the top-level processes and count them.

like image 36
Cascabel Avatar answered Sep 28 '22 07:09

Cascabel


you don't have to pass the result of pidof to wc to count how many there are..use the shell

r=$(pidof -x -o $$ test.sh)
set -- $r
if [ "${#@}" -eq 1 ];then
 echo "passed"
else
 echo "no"
fi
like image 34
ghostdog74 Avatar answered Sep 28 '22 08:09

ghostdog74