code checking

i was just wondering how would you check , beside the lock method, if an instance of another code is already running and if it is then output a message to the user saying the program is already running and exit!! the code is in BOURNE SHELLL!!!

thanks in advance!!

# prgname='test.sh'
# cat $prgname
sleep 120
# sh test.sh  &                   
[1]     25806
# if [ "$(ps -ef|awk '/'${prgname}'/ && !/awk/')." != "." ]
> then
> echo "${prgname} running !"
> fi
test.sh running !

thanks for replying, but i dont quite understand what you did!! i tried running it too and it doesnt work!!
plzzz help!!

thanks

# prgname='test.sh' # cat $prgname sleep 120 # sh test.sh  &                    [1]     25806

That part is telling ya to assign the script name to the variable prgname, what it does (the cat part) and he's executing it in background (&). You can see the process id of the script at the end (25806).

He's just showing you that the script is already running so you can test it.

# if [ "$(ps -ef|awk '/'${prgname}'/ && !/awk/')." != "." ] > then > echo "${prgname} running !" > fi test.sh running !

That part is the actual loop thats looking for the running script. [ ] Tests if the script is already running. If it does it echo's "(script name) running!". The last part is the actualy the result of the command which tells you ... yeah your script is running.

Back a bit... the test part.

[ ] this is the test part. So if [test] is true do something.

Test what? If the variable exist. If it exists you want to know.

ps -ef will list the processes (good thing to know if your looking for a process).

He's pipping it into a awk which will search for the variable prgname BUT will leave out awk. You always want to do this cause else it will always return with your actual search. See ex:

$ ps -ef | awk '/'ssh-agent'/'
user     1625 25793  0 10:55 pts/2    00:00:00 awk /ssh-agent/
user    20491     1  0 Sep19 ?        00:00:00 ssh-agent

You want the second one but not the first one. So the AND operator (&&) is really needed here to skip your search.

Ok ... last thing he does ... he assigns the result to a variable PLUS a dot "$(bla bla bla bla)."

See the trailling dot at the end? Thats actually needed incase your result is empty. If it is your variable will be a simple dot. That simple dot will be compared the other part of the test "."

That != says NOT equal so if it finds your script name that test will look like:

test.sh. (see the dot at the end of test.sh) NOT equal to dot

That test is true so do somehing.

In case its not running the test will look like this:

"." NOT equal to "." which is not true so it will skip the "do something part"

Hope it helped. Thats really the simplest i can do.