# What is the best way to ensure only one copy of bash script is running (in BSD)?



## ivand58 (Aug 5, 2011)

I my freebsd 7.0 box, there is no "lockfile" command

```
$ lockfile
-bash: lockfile: command not found
```
therefore I can't use the *lockfile* approach. 

So, what is the best way to ensure only one copy of bash script is running?


----------



## SirDice (Aug 5, 2011)

A really, really simple approach:

```
#!/bin/sh

if [ -f /var/run/somepid ]; then
 # Found a pid file
 ps -p `cat /var/run/somepid` > /dev/null
 if [ $? eq 0 ]; then
   # It's still running
   echo "Already running"
   exit
 fi
 # Stale pid file
 rm /var/run/somepid
fi
echo $$ > /var/run/somepid

# Do your stuff
```


----------



## ivand58 (Aug 5, 2011)

SirDice said:
			
		

> A really, really simple approach:
> 
> ```
> #!/bin/sh
> ...



Do I have to remove the pidfile (/var/run/somepid) at the end of my script?


----------



## poh-poh (Aug 5, 2011)

Is lockf(1) not adequate? If you want to block there is also pwait(1).


----------

