bash – Performing Atomic Write Operations in a File

bashcommand linelinuxsemaphore

After going through the bash documentation, this question and this one it's still not clear to me how can I perform atomic write (append) operations to a file in bash. I have a script that is run in multiple instances and at some point must write data to a file:

echo "$RESULT" >> `pwd`/$TEMP_DIR/$OUT_FILE

How is it possible to make all write operations from all concurrently running scripts to that file atomic (so that data from one instance doesn't overlap data from another)?

Best Answer

It seems you need to use flock as in the example from man (http://linux.die.net/man/1/flock)

(
flock -x 200

# Put here your commands that must do some writes atomically

) 200>/var/lock/mylockfile 

And put all your commands that must be atomic in ().

Related Question