@siguza I have been down this road before and settled on flock(1). If you haven’t already tried it I’d recommend giving it a whirl before doing any more shell crimes.
@siguza I have not found shlock(1) adequate in every situation but it does exist on macOS at least. If it doesn’t cut it for you good luck with your shell crimes—it’s dangerous to go alone, take this https://mywiki.wooledge.org/BashFAQ/045