handling multiple script instances in BASH

With flock you can implement basic job control in bash. That’s very handy when you have a script that is running in multiple instances and doing file operations. I was writing a script to return some data from a switch stack to zabbix and as zabbix does run the script for every item it gets from it’s discovery part, it is run very often.

So the different instances tried to do file operations at the same time. After a lot of trial and error i found flock.

flock 200
# commands to be run by only one instance of the script at the same time
) 200>/var/lock/mylockfile

that creates a lock file and before executing the part, bash checks if the lockfile is locked. Thanks at kiloroot.com.

Also remembering, that the linux move command is atomic, therefore very quick. It’s just changing meta-data. While copy can take a while, since it may need to handle a lot of data.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.