I have a bash script that may be run many times in parallel, and I need to be able to check the value in a file and modify it. Ideally, I'd like whichever script instance that gets there first to be able to do the reading and the writing without interference from another instance. I thought I could do this with flock, but it seems that some commands get ignored--I guess because they can't get a lock?
Here's what I have so far:
myfunc () {
{ flock -x 3 ; count=$(cat <&3); } 3< countfile
{ flock -x 3 ; echo $((count+1)) >&3; } 3> countfile
}
This is run from a subshell, so I have to do the counts via a file.
So, two things
- This is not using the same lock to read and write--I'd like that, but I'm not sure howto do it
- Why are my reads sometimes ignored?
Thanks!